Bud 'Mugur' Chirica Bud 'Mugur' Chirica - 4 months ago 10
HTML Question

Have the container width be as wide as it's first element, and other elements keep that maximum size

<div class="content">
<h2>This is a long heading</h2>
<p>This is a long text but it should be the same width as the h2, not wider nor narrower Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur temporibus commodi expedita debitis nisi accusantium, saepe dolorem sapiente eum suscipit quod vitae!</p>
</div>


Css

.content {
background-color: tomato;
color: #fafafa;
padding: 10px;
margin: 40px;
}


Basically my code is the first example, and i want it to be like in the second example.
The container having the same width as the H2(that is generated from a backend).

If the h2 has 2 words, then the paragraph below it should match the width, if the h2 has 20 words the same should happen(used extremes as guidelines).

Better check fiddle here

Looking for a css only solution

Answer

There is a way but it's not intended for general layout..but, FWIW.

For preference, I'd be using a more flexible layout method or javascript. I suspect that this option is not robust.

.content {
  display: table;
  border: 1px solid grey;
  /* note does not extend to paragraph */
}
.content h2 {
  display: inline-block;
}
.content p {
  display: table-caption;
  caption-side: bottom;
  text-align: justify;
}
<div class="content">
  <h2>This is a long heading</h2>

  <p>This is a long text but it should be the same width as the h2, not wider nor narrower Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur temporibus commodi expedita debitis nisi accusantium, saepe dolorem sapiente eum suscipit quod
    vitae!</p>

  <p>This is a long text but it should be the same width as the h2, not wider nor narrower Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur temporibus commodi expedita debitis nisi accusantium, saepe dolorem sapiente eum suscipit quod
    vitae!</p>
</div>

JSfiddle Demo

Comments