1

I have an HTML document with three elements. The first and third contain a fixed amount of text at fixed sizes.

The middle element, however, can vary widely in text length between loads of the page. I want to style it so that its font size is set to the largest one that will not result in the document overflowing the viewport.

A CSS-only solution would be ideal, but JavaScript is okay if needed.

I don't really know where to start, so I don't have any code. A previous, similar question doesn't cover my case, because the answers just use media queries to set different font sizes for different screen sizes.

user229044
  • 232,980
  • 40
  • 330
  • 338
Someone
  • 121
  • 1
  • 7
  • get the element width with JavaScript and calculate the font with u need. – StefanBD Dec 15 '22 at 20:55
  • @StefanBD so it can't be done with pure CSS? – Someone Dec 15 '22 at 21:00
  • maybe, the JS Way is people bring u to hell :X, im not so fit in css but i think there are ways because we have already mediaquerys maybe there's something for element with. – StefanBD Dec 15 '22 at 21:05
  • https://stackoverflow.com/questions/16056591/font-scaling-based-on-width-of-container Viewport Sized Typography seems a good hint – StefanBD Dec 15 '22 at 21:06
  • @StefanBD thank you, but those answers seem to assume the text will be somewhat consistent in length. The longest possible text in my case is about a hundred times longer than the shortest one. – Someone Dec 15 '22 at 21:32

1 Answers1

0

This idea could be useful for your problem as a starting point. Im'using svg to insert text. Note that resizing the browser the text remain perfectly inside the box though the box change the size. It's difficult to explain how it works however each tspan tag is a line of text, the text is placed starting to the left, the baseline is the border-top thus the dy attribute is fundamental. x attribute is alike left in position:absolute in css.

      .typographic-lookup {
            width: 30%;
            border: 1px solid black;
         }

         .typographic-lookup .span-1 {
            font-size: 30px;
         }

         .typographic-lookup .span-2 {
            font-size: 26px;
         }
     
   
      <h2 class="typographic-lookup">
         <svg viewbox="0 0 150 120">
            <text>
               <tspan class="span-1" x="6" dy="0.8em">Prima riga</tspan>
               <tspan class="span-2" x="3" dy="0.75em">Seconda riga</tspan>
            </text>
         </svg>
      </h2>
  
Nick
  • 1,439
  • 2
  • 15
  • 28