How does this pseudo-element work?

I don't want to change the markup, and I just want to know the reason for the pseudo-element that it works.

demo code

div{
    border: 1px solid #000;
    height: 300px;

}
div:before{
    content: "";
    height: 100%; 
    display: inline-block;
    vertical-align: middle;

}

      

enter image description here

and narrowing down the browser:

enter image description here

So why is only one line of a paragraph aligned? If you try to use vertical-align: bottom;

, you will see it at the bottom and all the lines of the paragraph will be there.

But I'm just curious to know why one line of them works vertically aligned?

+3


source to share


1 answer


The height of your pseudo element is 100% of div

. Since it is an inline-block pseudo-element :before

, this increases the effective line-height of the first line to 300 pixels, leaving the rest of the lines unaffected. The rest of the text on the first line is then exposed vertical-align: middle

on your pseudo-element as it is on the same line as your pseudo-element. See section 10.8 of the specification .

If you change the line-height of the pseudo-element :first-line

instead of the pseudo-element :before

, you get a similar effect :



div {
    border: 1px solid #000;
    height: 300px;
}
div:first-line {
    line-height: 300px;
    vertical-align: middle;
}

      

But the concept should be much clearer as you are actually styling the first line of text directly, rather than using a pseudo-element to affect the margin of the first line.

+3


source







All Articles