Theo Chirica
Theo Chirica

Reputation: 4516

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

Upvotes: 2

Views: 78

Answers (2)

Paulie_D
Paulie_D

Reputation: 115278

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

Upvotes: 1

holden
holden

Reputation: 1779

The only way that ensure a robust backward compatibility is Javascript. I'd avoid the "table" display; i can't recall all the supports situation but it's somehow problematic. I'd add that i don't find that nice coding using Divs just to trasform them in Tables again...

All in all it's just 2 lines of code:

function setWidth(id) {
 w=$("#header").css("width");
  $(id).css( "width", w);
}
setWidth(inner)

css part:

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

 }
 h2 {
    display:inline
  }

HTML:

<div class="content">
   <h2 id="header">This is a long text</h2>
   <p id="inner">This is a text that expands accordling with H2 header other text, other and other...</p>
</div>

Working Feedle here

Upvotes: -1

Related Questions