Drunken Master Drunken Master - 4 months ago 21
CSS Question

Apply width to :first-line

I would like to have a heading with the first line shorter than the rest of it.

Here is some code:



div {
width: 20em;
border: 1px solid #000;
}
h3:first-line {
background-color: yellow;
width: 10em;
}

<div><h3>Lorem ipsum dolor sit amet who made up this fake Latin text</h3></div>





The first line is highlighted to demonstrate that background-color can be applied, but not the width, unfortunately.

How can I apply a width to the :first-line pseudo element?

Answer

You can't specify the width of the ::first-line pseudo element. For a list of properties you can apply to ::first-line, see MDN ::first-line.

Workaround:

You can make the first line shorter with a right floated pseudo element :

div {
  width: 20em;
  border: 1px solid #000;
  line-height: 1.2em;
}
h3:first-line {
  background-color: yellow;
}
h3:before {
  content: '';
  float: right;
  width: 10em;
  height: 1em;
}
<div><h3>Lorem ipsum dolor sit amet who made up this fake Latin text</h3></div>

Comments