'Center inline text as if it were inline-block

I am building this design, which looks so simple, but I'm having difficulty centering it, while keeping the text left-aligned.

enter image description here

I made the heading display:inline because I need the background to only span the actual text as opposed to the full width of the block. But I need to center the block while leaving the text left-aligned. So I wrapped the text in a div with a max-width, and then centered the div.

 <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;
}

Problem solved. Except not. Because this needs to be repeatable for headings of varying lengths. A short headline isn't going to appear centered if the wrapper is wider. I could use text-align:center when the headline is short enough to be on one line, but since the site is responsive, that's not guaranteed.

I also tried using the <mark> tag but that didn't do anything differently.

Here's a fiddle of things I've tried.

Is there a CSS solution? (If not, I'm open to JS if it's not too bad for performance.)



Solution 1:[1]

I think the best I can come up with is to add display:table to the wrapper div. This correctly centers short headlines that don't take up the full max-width. For longer headlines that break to 2 lines, I still get mixed results on how precisely centered it looks, unless you manually add a line break between the lines. (Which I don't want to do because lines need to adjust responsively.) But I guess this is the only CSS-based option. I'll wait a couple days to mark this correct in case anyone swoops in with a better idea.

.highlight-wrapper {
    max-width:60%;
    margin:0 auto;
    display:table;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LBF