Add Line Breaks to CSS Generated Content

Advertisement

You’re probably familiar with CSS generated content, and how it is used in conjunction with the :before & :after pseudo-elements. Maybe you read our article on replacing text with CSS.

A common question we get is, “How can I add a line break to my CSS content?”

Good news! Line breaks are possible with CSS, but there’s a little more to it than just inserting an entity conversion code into your content declaration.

How to Add Line Breaks to the CSS Content Property

Let’s start with some really simple HTML. Your HTML could almost be anything. It’s not really important with this example. All that really matters is how we treat the pseudo-element.

<p>I love CSS!</p>

Now, let’s say you want to add a line of text below that using CSS content.

p:after {
	display: block;
	content: "Me too!";
}

Easy enough. Nothing new here. You need to use display: block; because the default display value for pseudo-elements is inline.

Now you want to add another line below “Me too!”, but still using the CSS content property. Your CSS would look like this:

p:after {
	display: block;
	white-space: pre;
	content: "Me too! \A Me three!";
}

The \A escape sequence will insert a line break. It works the same as adding a <br /> tag to your HTML.

The CSS spec for content goes into more detail, or you can get a refresher on the white-space property.

NOTE: You could also use white-space: pre-wrap;.

A Caveat on Line Breaks with CSS

There are very few scenarios where I would use this technique. If you have control over your markup, there are better ways to insert & manipulate content. CSS generated content should be used sparingly when dealing with actual text & line breaks.

Advertisement

Dave Warfel

Bio coming soon…

One thought on “Add Line Breaks to CSS Generated Content

Leave a Reply

Your email address will not be published. Required fields are marked *