Aligning text differently depending on whether it is multiline?

I am looking for a CSS solution to align text differently depending on whether it breaks across multiple lines or not. No Javascript, thanks. However, I'm happy with the browser support.

This is what I want to achieve:

enter image description here

When the text content only fills one line, I want it to stick text-align: center;

. Otherwise I would like it to be text-align: left

.

I know that I could assign different Javascript based classes based on:

  • Characters
  • element height vs line-height

But these solutions are not general and have many complications. What I'm looking for is a CSS (possibly CSS3) solution to a problem that has eluded me so far.

+3


source to share


1 answer


Here's a clean CSS solution:

div {
   background-color: yellow;
   width: 200px;
}
  
div span {
   display: inline-block;     
   position: relative;
   left: 50%;       /* move content to the right until the left side is aligned to the middle of the div container (at 100px)  */
   -webkit-transform: translateX(-50%); /* move half of content width back to the left. This centers content.*/ 
   -moz-transform: translateX(-50%);
   transform: translateX(-50%);
}
      

<div>
  <span>this is a single line content</span>
</div>
<br />
<div>
  <span>this is a single line</span>
</div>
<hr />
<div>
  <span>this is an example of multi line content</span>
</div>
<br />
<div>
  <span>this is an example of very long multi line content that occupies three rows</span>
</div>
      

Run codeHide result


By placing your content in inline-block

, you will get the width of such content, bounded inside the container div.




If you cannot add an extra element ( span

) to your markup, still you can do what you want with only divs.

div {
  background-color: yellow;
  max-width: 200px;
  display: inline-block;
  position: relative;
  left: 50%;
  -webkit-transform: translateX(-50%);
  -moz-transform: translateX(-50%);
  transform: translateX(-50%);
}

      

However, the yellow background only covers the content area, not 200 pixels. I've tried using pseudo-elements to :before

no avail.

+8


source







All Articles