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
You can set the max-width yourself, 700 seems fine.
try this:
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/
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:
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)