Line-height affecting spacing above first line and after last line

后端 未结 1 445
情书的邮戳
情书的邮戳 2021-01-04 04:27

I\'ve a text in side heading with multiple lines. Want the spacing the two lines to increase, so I set a line-height. When I do this, not only does it increase space between

相关标签:
1条回答
  • 2021-01-04 05:28

    You can use negative margins for this, although there is something to keep in mind:

    line-height is a funny thing. According to CSS2.1 it doesn't specify the line-height but the minimum height of line-blocks:

    On a block container element whose content is composed of inline-level elements, 'line-height' specifies the minimal height of line boxes within the element. The minimum height consists of a minimum height above the baseline and a minimum depth below it, exactly as if each line box starts with a zero-width inline box with the element's font and line height properties. We call that imaginary box a "strut." (The name is inspired by TeX.).

    A line box is defined in 9.4.2 Inline formatting contexts:

    In an inline formatting context, boxes are laid out horizontally, one after the other, beginning at the top of a containing block. Horizontal margins, borders, and padding are respected between these boxes. The boxes may be aligned vertically in different ways: their bottoms or tops may be aligned, or the baselines of text within them may be aligned. The rectangular area that contains the boxes that form a line is called a line box.

    This doesn't change in CSS3 very much, at least if you don't change the line-stacking. However, there is no property which targets your problem directly: you can't change the line-height of the ::first-line, it will always get applied.

    That said, use negative margins for the time being. Even better, wrap your elements in a generic container. By using :first-child and :last-child you can add as many elements as you like.

    Example

    <div>
        <h1>I've a text in side heading with multiple lines. Want the spacing the two lines to increase, so I set a line-height. When I do this, not only does it increase space between the two lines, it also increases spacing above the first line.</h1>    
        <h1>I've a text in side heading with multiple lines. Want the spacing the two lines to increase, so I set a line-height. When I do this, not only does it increase space between the two lines, it also increases spacing above the first line.</h1>
    </div>
    
    body {padding:30px;background:yellow;border:1px solid red;margin:0}
    div{background:red;margin:0;padding:0;border:1px solid green;}
    h1{line-height:2em;}
    div > h1:first-child{
        margin-top:-.25em;
    }
    div > h1:last-child{
        margin-bottom:-.25em;
    }
    
    0 讨论(0)
提交回复
热议问题