Home > Net >  Center inline text as if it were inline-block
Center inline text as if it were inline-block

Time:03-30

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 >
      <h2 >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.)

CodePudding user response:

I'd make this a comment, but I don't have enough reputation yet. Perhaps the least hacky way to do this is to split the lines of text into distinct HTML elements, then put them all inside a <div> and style them from there. If the contents of the heading are dynamic or you want to reuse this heading style, I guess you'd need some JS to split the text into appropriately sized lines.

CodePudding user response:

Try adding max-width: fit-content; to the wrapper div.
You can probably do it on the heading tag directly.
Or something like width: fit-content; and max-width: 100%; etc.

.highlight {
  display: inline;
  position: relative;
  border-left: 6px solid red;
  -webkit-box-decoration-break: clone;
  background: #2056a7;
  color: white;
}

.highlight-wrapper {
  max-width: fit-content; /* NEW */
  margin: 0 auto;
  outline: 4px solid green;
}
<div >
  <h2 >This is a highlighted headline lorem ipsum dolor sit.</h2>
</div>

  • Related