Limit paragraph width to header width

Viewed 674

I have a header: <h1>Unknown width</h>

I also have a paragraph underneath the header: <p>Lorem ipsum dolor sit amet</p>

I'm trying to limit the width of the paragraph to the width of the header. When the screen's size changes, the header may wrap, occupying two or more lines. In that case, I want the paragraph to be limited to the width of the longest line.

I want something functionally equivalent to this make-believe CSS:

#header {
    // header style
}

.paragraph {
    max-width: header.width;
    text-align: justify;
}

Or this:

.container {
    width: fit-content except paragraph;
}

.header {
    // header style
}

.paragraph {
    width: 100%;
    text-align: justify;
}

Is this possible without using JavaScript? Is it possible with/without media queries?

1 Answers

You can use CSS variables and set the main header width like this:

:root {
 --header-width: 50%;
}

And make the p tag responsive by using word-wrap: break-word;

Take a look on this code:

:root {
  --header-width: 50%;
}

#header {
    width :  var( --header-width);
    border : 1px solid black;
}

.paragraph {
    word-wrap: break-word;
    max-width :  var( --header-width);
    border : 1px solid black;
}
<h1 id="header">Unknown width</h1>
<p class="paragraph">Lorem ipsum dolor sit amet asfasfasfasfasfsafassafsafasfasfasfsafasfsafasfasfasfasfasfasfasfasfasfasfasfasfasfasfasfasfasfasfasfasfsafasfasfasfasfasfasasfasfasfas</p>

Related