Make h1 decide the div width

Viewed 311

I'm trying to set the div width to be decided by h1. So the header can be as wide as it wants to be, while the paragraph will only be as wide as the header.

<div>
  <h1></h1>
  <p></p>
</div>

I've heard that this is impossible in plain html/css. Is this true? If so, what would a solution look like?

3 Answers

I typically have used a width:0; min-width:100%; combo on an internal wrapper to achieve this. You also need to collapse the width of the div by either floating it or setting it to display:inline-block;. It's important to keep the h1 outside of the wrapper so that it can force the width of the collapsed width div.

div {
  float: left;
  clear: left;
  margin-bottom: 1em;
}

p {
  width: 0;
  min-width: 100%;
}

h1, p {margin: 0;}
<div>
  <h1>This is a test</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>

<div>
  <h1>This is a test with a very long title</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>

<div>
  <h1>Short</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>

<div>
  <h1>This is a test with a title that is absurdly long with the hope that it will wrap in the final result.</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>

Set div-s display value to inline-block:

div {
    display: inline-block;
}

But since h1 has width of 100%(is block element) then it's going to be as wide as some other parent is. If you want heading not to be 100% width then make it aswell inline-block:

h1 {
    display: inline-block;
}

Example: https://jsfiddle.net/cr29y1tc/32/

As said by @Roland Ruul i've added some colours to visualise the fact that inline-block is what you need to do.

https://jsfiddle.net/L5eyd4bv/2/

<div>
    <h1>Content goes here</h1>
    <p></p>
</div>

div {
    background-color: red;
    display: inline-block;
}

h1 {
    background-color: green;
}
Related