How does line-height vertically center text?

前端 未结 5 487
别跟我提以往
别跟我提以往 2021-02-07 07:51

I\'m trying to understand why the line-height CSS property places the text vertically in the middle of this button:

相关标签:
5条回答
  • 2021-02-07 08:28

    Whenever a paragraph is inserted in a division the distance between the first line and the top border of the div is half of the line-height i.e if the default line- height is 1px then the distance between the first line and the top-border of the div is 0.5px.

    If you have a division with height:58px the distance between the line and the top-border of the div is 29px and the distance between the line and the border of the bottom div would be=(total div height-distance b/w the line and the top border) which is 58px-29px=29px.This results in the line being vertically aligned at the center.

    Also,there is no need to use vertical align:middle(for text containing not more than one line) if you're using line-height to centrally align the text.

    0 讨论(0)
  • 2021-02-07 08:30

    it is by design. If the CSS parser (i.e. the browser) doesn't know how tall is your text, he can't vertical align your text correctly.

    Note there is a default value of line-height property.

    0 讨论(0)
  • 2021-02-07 08:35

    line-height defines the height of text which make the paragraph looks neat so vertical-align works with respect to line-height when you increase the line height it increases the height and the you can more clearly see the effects of vertical-alignment of text

    think this as a notebook which we children use to learn English -writing in nursery class

    0 讨论(0)
  • 2021-02-07 08:39

    The line-height property is essentially setting a 29px (29 + 29 = 58) text line above and below your text, "Complete Order". If you added another line of text below this you will find it 58px below this text. You are putting line-height here only to center your text in the middle.

    Here is a good slide show to help you understand this concept more... line-height

    And here is an example using your code of what I am talking about: http://jsfiddle.net/YawDF/14/

    By setting the line-height to 58px you are telling the browser to leave half this above and below the text line, creating a '58px' gap between each line and only a '29px' gap above the first line.

    SIDE NOTE: Your use of vertical-align: middle is useless in the code you are showing. This can be taken out all together.

    0 讨论(0)
  • 2021-02-07 08:51

    The text you generate is inside its own line box and vertical-align is used for placement inside that box. However, that box has nothing to do with the div you have wrapped around the text. You set the height of the div to 58px but that does not affect the height of the line text box. That is why you need line-height to match the height of the div.

    0 讨论(0)
提交回复
热议问题