::first-line

Sara Cope on Updated on
##description##
Ad
`, } ); } })();

The ::first-line pseudo-element is for applying styles to the first line of an element. Imagine a paragraph that is several lines long (like this one!). ::first-line allows you to style that first line of text. You could use it to make it larger or set it in small-caps as a stylistic choice. The amount of text targeted by this pseudo-element depends on the several factors like line length, viewport width, font-size, letter-spacing, word-spacing. As soon as the line breaks, the text after that is no longer selected. Note that there is no actual DOM element being selected here (thus “pseudo” element).

This pseudo-element only works on block-level elements (when display is set to either block, inline-block, table-caption, table-cell). If set on an inline element, nothing happens, even if that inline element has a line break within it.

Also note that not all properties can be used in a ruleset containing ::first-line. Mostly:

.element::first-line {
    font-style: ...
    font-variant: ...
    font-weight: ...
    font-size: ...
    font-family: ...

    line-height: ...
    color: ...
    word-spacing: ...
    letter-spacing: ...
    text-decoration: ...
    text-transform: ...

    background-color: ...
    background-image: ...
    background-position: ...
    background-repeat: ...
    background-size: ...
    background-attachment: ...
}

The official CSS specification tells User Agents can allow other properties if they feel like it:

UAs may apply other properties as well.

A word regarding specificity

The following demo shows how ::first-line is able to override any kind of specificity, even !important.

This is because the pseudo-element is treated like a child element, not just a part of the parent element. So the rules you apply to it are just for it, the parent rules just may cascade to it.

Also, try resizing your browser to see how behave the pseudo-element when the viewport width change.

There is no :last-line or :nth-line, even though that would be cool.

Browser support

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

ChromeFirefoxIEEdgeSafari
93.59125.1

Mobile / Tablet

Android ChromeAndroid FirefoxAndroidiOS Safari
14614835.0-5.1

More information