-3

I would like to stretch a single word across a div container.

For instance, this word inside a div enter image description here

should be stretched like this:

enter image description here

The solution I found was to wrap each letter inside a span tag, treat them as flex items, and simply apply justify-content: space-between:

HTML

<div>
  <span>W</span><span>O</span><span>R</span><span>D</span>
</div>

CSS

div {
  font-size: 32px;
  width: 50%;
  background-color: #89CFF0;
  padding: 1rem;
  display: flex;
  justify-content: space-between;
}

This works, however, I would not like to wrap each letter inside tags.

Question: Is there a way to stretch a word across a container without wrapping each letter in tags and without use of jQuery? Furthermore, wrapping the letters inside tags using JS is also an option I would like to avoid, because it is essentially the same as the solution above.

For instance, just having a word inside a div like this to be stretched across the width of the container

<div>
  WORD
</div>

I would like to know if there is a way to solve this issue with CSS or/and vanilla JS only.

galaxyworks
  • 321
  • 1
  • 2
  • 10

1 Answers1

3

Unfortunately the promising-looking text-justify is not yet implemented fully on most browsers (and may not be).

text-align however is supported in most browsers and text-align-last which tells the browser to justify the last line even if it is short, is supported in many of the main browsers. But not Safari sadly, so we introduce a bit of a hack - force the thing to look full width by adding a pseudo element.

I can't see a way of just having a single word justified this way, but you can put spaces between each character, thus avoiding the need for extra elements:

* {
  margin: 0;
  padding: 0;
}
div {
  width: 100vw;
  text-align: justify;
  text-align-last: justify;
}
div::after{ /* hack added for Safari */
   content: "";
   display: inline-block;
   width: 100%;
}
<div>W O R D </div>
A Haworth
  • 30,908
  • 4
  • 11
  • 14
  • While this seems to be about the best answer, I have to report a slight bug/problem (Firefox 89/Ubuntu 20.04) in which the last letter - D in the example - is partially off-screen on the right hand side, consistently whether full-screen or "inline" in the answer. – David Thomas Jun 26 '21 at 18:51
  • 1
    @DavidsaysreinstateMonica it's because of the width:100vw not really needed and can be removed – Temani Afif Jun 26 '21 at 19:37
  • 1
    @DavidsaysreinstateMonica thanks for spotting. Normally I'd remove the default padding and margin from all - so it's not so much a bug, the width of the element is probably right, as my sloppiness. – A Haworth Jun 26 '21 at 20:47