<p> block with line break after each word and width limited to longest word

Viewed 68

I want to have a <p> element with 1-3 words inside, so each new word will take a new line. Ideally, I want to make the <p> element as wide as the longest word. I cannot insert <br> or other html, as the data comes from a 3rd party api.

Right now the only way I found is to fix the <p> length, but with long words the result is rather ugly.

Any CSS alternative? Cheers!

p {
  max-width: 48px;
  background-color: blue;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  word-break: break-all
}
<p>extra super tag</p>
<p>extra tagverylong tag</p>

2 Answers

Use width:min-content

p {
  width: min-content;
  background-color: blue;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
}
<p>extra super tag</p>
<p>extra tagverylong tag</p>

Another trick using inline-block for better support

p {
  display:inline-block;
  background-color: blue;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
}

.main {
  width:0;
}
<div class="main">
  <p>extra super tag</p>
  <p>extra tagverylong tag</p>
</div>

Also with table:

p {
  display: table;
  width: 1px;
  background-color: blue;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
}
<p>extra super tag</p>
<p>extra tagverylong tag</p>

Add

word-spacing: 100vw;

to your style.

p {
  max-width: 48px;
  background-color: blue;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  word-break: break-all
  word-spacing: 100vw;
}
Related