skip to Main Content

I have an h1 element that can contain a very short and long word. Moverever, it has a 64px font-size.

The h1 element is in in section element which has 736px max-width.

If the word is very long, it goes over its container and over the documentElement on mobile. for example:

h1 {
  font-size: 64px;
}
<h1> 
  Transmissionselektronenmikroskop
</h1>

<h1> 
  Mikroskop
</h1>

I can use CSS to break it, but the problem is the browser might break it from somewhere that it may not be a good fit.

I can use <wbr> element to let the browser break these words from where that I prefer. However, it is cumbersome and I might have many more long words in the future.

I rather prefer to change font-size than breaking it.

How to set as much font-size such that h1 does not overflow?

I want to change the font-size of h1 only if it overflows otherwise.

4

Answers


  1.  @media only screen AND (max-width: 700px) {
      h1 {
       font-size: 100%;
      }
     }
    

    You can set the max-width yourself, 700 seems fine.

    Login or Signup to reply.
  2. try this:

    h1 {
     font-size: 64px;
     max-width: 100%;
     overflow-wrap: break-word;
    }
    
    Login or Signup to reply.
  3. If your container is full-width (i.e. spans the full width of the viewport / browser window), you could use the vw unit for your font-size setting (1vw = 1% of the viewport width, i.e. a relative setting)

    Otherwise you might also want to use fittext, a script that calculates font-size depending on the container width (not only viewport): http://fittextjs.com/

    Login or Signup to reply.
  4. If you don’t want to break the word and just want to change the font-size I think that js is the only way, something like that:

    const wrapper = document.querySelector('.wrapper');
    const wrapperWidth = wrapper.clientWidth;
    const allTitles = wrapper.querySelectorAll('h1');
    
    
    allTitles.forEach(title => {
      if(title.clientWidth > wrapperWidth){
        const titleFontSize = window.getComputedStyle(title, null).getPropertyValue('font-size');
    
        const newFontSize = parseInt(titleFontSize) / (title.clientWidth / wrapperWidth);
        title.style.fontSize = newFontSize + 'px';
      }
    });
    h1{
      font-size: 64px;
      width: fit-content;
    }
    .wrapper{
      width: 100%;
      max-width: 400px;
      background-color: green;
    }
    <div class="wrapper">
      <h1> 
        Transmissionselektronenmikroskop
      </h1>
    
      <h1> 
        Mikroskop
      </h1>
    </div>

    With this, all the h1 that are bigger than the parent box will be set to a font-size that allows all the text to be shown (this the example on a wrapper that is 400px, but it will work on everything, just remember to apply the "width: fit-content" to the h1)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search