2

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?

Audiopolis
  • 530
  • 5
  • 24
  • Can you use the Javascript/HTML/CSS snippet function to make an example? I'm having difficulty imagining your scenario. By default, paragraphs and text both wrap to fit their box - even if that box is constrained by window size. Are you otherwise setting the width of the texts' boxes some other way? – erik258 Aug 23 '20 at 16:16
  • You need to wrap both header and paragraph in a div and move the styles from header to that parent div. – Mohammad Usman Aug 23 '20 at 16:20

1 Answers1

0

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>
tomer raitz
  • 390
  • 2
  • 10
  • I don't want to set the header's width to 50%. I just want its width to fit the text in the header. I don't want to specify a width for it at all. The snippet shows a header of 50% width (wider than it needs to be) and a paragraph of 50% width. This answers my question: https://stackoverflow.com/questions/55040250/how-to-match-width-of-text-to-width-of-dynamically-sized-image-title – Audiopolis Aug 25 '20 at 13:23