0

I have a parent element which is set to display: grid with an image for the background of the section and a child div within this section that spans the entire size of the grid and contains a h1 and h2 tag.

I have an unspecified length of text that will be entered in the h2 tag. The h2 tag height will expand and overflow the grid size to compensate for extra length of the string.

I am trying to keep the string within the grid regardless of the string length and dynamically change the font-size to compensate for the length of the string.

The font should dynamically change size to be smaller if the length of the string means that the div will overflow. When the width of the div reduces (due to different viewport sizes), then the text needs to reduce inside also, but stay within the parent element size and never overflow.

Diagram for visual representation:

enter image description here

<section>
        <img src="image-link-here.jpg" alt="an image"/>
        <div>
            <h1>
                Title
            </h1>
            <h2>
                A very long string
            </h2>
        </div>
    </section>

The div containing the h2 seems to be within the size constraints of the parent section, but the h2 element itself seems to be overflowing. I have tried using vh and vw css properties on the font-size for these elements but it is still overflowing.

I cannot use javascript, I am asking if this is possible in CSS

  • 1
    You are probably going to need Javascript to calculate a suitable font size. Is that acceptable? – A Haworth Jun 29 '22 at 06:45
  • If you know beforehand what text is going to go in there, you can use a bunch of media queries to make sure the`font-size` is always small enough that it doesn't overflow. Just use trial and error to figure out what works. If you don't know what text is going in there, but it's not important that all of the text is shown, you can use `text-overflow: ellipsis` with `overflow:hidden` to cut off the overflow with an ellipsis. Otherwise you will have no other choice but to use JavaScript. – hostingutilities.com Jun 30 '22 at 02:19

0 Answers0