35

I have a div element that holds one line of text. How can I get this text to fill the width 100%?

text-align:justify is only working on elements with several lines of text, and has no effect on the div with single line. Manually adjusting the letter-spacing and word-spacing is ugly and ineffective.

Are there any other alternatives?

Jones Joseph
  • 4,703
  • 3
  • 22
  • 40
Alix Përry
  • 449
  • 2
  • 7
  • 14
  • 1
    The conventional way to solve this is to use an `:after` pseudo element to generate enough content to make the content flow onto a second line, then tinker with font-size, line-height, height, and overflow to hide the extra vertical space that this causes. – Alohci Jan 18 '14 at 01:55

2 Answers2

53

Try this:

div {
  text-align: justify;
}

div::after {
  content: "";
  display: inline-block;
  width: 100%;
}
<div>
  Some sample testing string
</div>

jsFiddle

Take a look here for more info.

InSync
  • 4,851
  • 4
  • 8
  • 30
mutil
  • 3,205
  • 1
  • 27
  • 34
  • 2
    Using that trick to justify a oneliner title, I had to force the height of my element to prevent it for adding a new empty line under my title. – svassr Oct 21 '14 at 23:38
  • @svassr or you can also add a ::before pseudo element and then just tweak the line-height on the parent element, this way the text being always centered between the two pseudo elements. All in all, nice solution @mutil! – Nicolae Olariu Feb 06 '15 at 10:53
1

The modern way to do this is with text-align-last: justify

Alec
  • 2,432
  • 2
  • 18
  • 28