Apply Background Color on Text Spanning Multiple Lines

css
Published on March 22, 2021

While applying a background color for a text that spans to multiple lines, the full container gets filled with the color. However the need is to apply the background color only on the text.

The problem can be solved by setting the text container as a inline element, rather than a block element. The box-decoration-break property can also be used to apply padding to each line of text, rather than applying it only to the container.

Example

Apply Background Color on Text Spanning Multiple Lines with CSS

HTML & CSS :

<!- text is contained within a span which is an inline element -->
<h2><span>Apply Background Color on Text Spanning Multiple Lines with CSS</span></h2>
h2 {
	font-size: 50px;
	color: white;
	text-align: center;
}

h2 span {
	background-color: #16a085;
	padding: 6px;
	-webkit-box-decoration-break: clone;
	box-decoration-break: clone;
	line-height: 100px;
}
In this Tutorial