Having a simple issue that I believed could easily be solved with modern CSS, but I'm now confused. I was aiming to have the background of a text parent span precisely across the width of its longest text line, evenly spreading on the sides, different from how the span element behaves.
Block elements naturally occupy 100% width, and inline-block would have been fine if not for the auto-wrapping mechanism of text, which sizes the bounding box to 100% as it wraps to the line below for the first time.
I simulated the desired effect, but these workarounds seem somewhat messy. I'm looking for a simpler, native solution.
Fiddle + simulation: https://jsfiddle.net/sxmkonLp/20/
Standard block element text
<div class="container normal">
<h1 class="fill">Gonna wrap my text around</h1>
</div>
Parent element display: "inline-block" (slightly closer)
<div class="container">
<h1 class="fill inl-blk">Gonna wrap my text around</h1>
</div>
Text inside "span" element (closer to what I need, but not evenly spread on the sides, varies based on each line's length)
<div class="container">
<h1>
<span>Gonna wrap my text around</span>
</h1>
</div>
Desired result (emulating text breaks with br and classes)
<div class="container text-span">
<h1 class="fill2 inl-blk">Gonna<br class="sm4"> wrap<br class="sm3"> my<br class="sm2 sm4"> text<br class="sm1 sm3 sm4"> around</h1>
</div>
CSS for the markup
html, body {
text-align: center;
margin: 0;
padding: 0;
}
.container {
padding: 10px;
width: auto;
background: orange;
margin: 10px;
}
.container span {
background: lightgreen;
padding: 5px;
}
.inl-blk {
display: inline-block;
}
.fill {
background: yellow;
}
.fill2 {
background: blueviolet;
color: white;
}
.sm1,.sm2,.sm3,.sm4 {display: none;}
@media screen and (max-width: 470px) {
.sm2 {display: none;}
.sm3 {display: none;}
.sm4 {display: none;}
.sm1 {display: block;}
}
@media screen and (max-width: 350px) {
.sm1 {display: none;}
.sm3 {display: none;}
.sm4 {display: none;}
.sm2 {display: block;}
}
@media screen and (max-width: 295px) {
.sm1 {display: none;}
.sm2 {display: none;}
.sm4 {display: none;}
.sm3 {display: block;}
}
@media screen and (max-width: 242px) {
.sm1 {display: none;}
.sm2 {display: none;}
.sm3 {display: none;}
.sm4 {display: block;}
}
In the last example (purple box), you can see that the background occupies the exact space of the text boundary. The challenge is achieving this while the text automatically wraps to the line below.
I recently stumbled upon some interesting CSS properties like "box-decoration-break: clone;" which makes a span's content resemble separate block lines, yet still extends across varying line lengths, rendering it unsuitable for my current requirements. It would be fantastic to have a CSS property specifically for that.