Currently working on a design that appears deceptively simple, yet I'm encountering challenges in centering it while keeping the text aligned to the left.
https://i.sstatic.net/qhf6p.png
In an attempt to have the background span only the actual text width, not the entire block, I opted for the display:inline
property for the heading. Subsequently, I enclosed the text in a div with a max-width and centered the div element to achieve the desired alignment.
<div class="highlight-wrapper">
<h2 class="highlight">This is a highlighted headline lorem ipsum dolor sit.</h2>
</div>
.highlight {
display:inline;
position:relative;
border-left:6px solid red;
-webkit-box-decoration-break: clone;
background:#2056a7;
color:white;
}
.highlight-wrapper {
max-width:60%;
margin:0 auto;
}
Issue resolved? Not quite. The approach falls short when dealing with headings of varying lengths. Short headlines may not appear centrally aligned if the wrapper width exceeds their length. While using text-align:center
could work for single-line titles, it's impractical due to responsive design considerations.
I also experimented with the <mark>
tag, but witnessed no notable changes in results.
Refer to this fiddle showcasing my attempts thus far.
Seeking a CSS-based solution. Open to JavaScript alternatives as long as performance impact remains minimal.