设定行高2种方式

  • 使用width、height(假定现宽38,高22 ;目标宽70,高30)

    1. .welcome{
    2. width: 70px;
    3. height: 30px;
    4. line-height: 30px;
    5. text-align: center;
    6. }
  • 使用padding

    1. .welcome{
    2. padding: 4px 16px;
    3. line-height: 22px;
    4. }

CSS设定行高、绝对定位 - 图1

补充

  1. 使用width、height 时若文字发生变动会出现bug(显示不全)
    CSS设定行高、绝对定位 - 图2
    CSS设定行高、绝对定位 - 图3
  2. 使用padding时,目标高度30px减现高度22px得出上下内边距为4px,左右同理;不同机器现行高可能存在差异,通过设置line-height固定值消除bug

    绝对定位

    思路:
  • 子元素absolute
  • 父元素relative
    子元素相对于父元素定位
    1. .welcome{
    2. position: relative;
    3. }
    4. .welcome .triangle{
    5. position: absolute;
    6. left:4px
    7. top:100%;
    8. }

补充:子元素位于父元素下方(使用top属性),子元素相对于父元素移动(使用left)
综合应用
效果图
CSS设定行高、绝对定位 - 图4
代码

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style>
  5. .welcome{
  6. background:red;
  7. color:white;
  8. padding:4px 16px;
  9. line-height:22px;
  10. position:relative;
  11. }
  12. .inner{
  13. display:block;
  14. border: 10px solid transparent;
  15. width:0px;
  16. border-left-color:red;
  17. border-top-width:0px;
  18. position:absolute;
  19. left:6px;
  20. top:100%;
  21. }
  22. </style>
  23. </head>
  24. <body>
  25. <span class="welcome">Hello<span class="inner"></span></span>
  26. </body>
  27. </html>