Full width CSS & JS scalable header

Hi! Today I’m going to show you a small thing I had to create for one of my clients – the full width text header. After looking for existing solution I decided to write one by myself. Let’s go!

The methods I’ve found on the internet were based on scaling text using font-size attribute. They’ve used following steps:

  1. Check if the text fits with the initial size.
  2. Increase the font-size by one unit until the width of the text element will become greater than its container.
  3. When the width of the text element is greater decrease its font size to fit the container.

Problem with this method is that it’s not precise enough and it requires a lot of calculations. What if we have many full-width elements on our site? It’ll take ages to make calculations. Speaking of the precision – if we set our unit to 1px, we can’t set the width of our text to fit its container perfectly, also the lower unit we use (ie. 0.5px) the more calculations will be done. So what can be done here? We will use transform: scale to make things better (and waaay faster).


My concept is based on CSS transformations and it uses one division operation to calculate the perfect element size. Let’s have a look at the steps of my algorithm:

  1. Get the unscaled width of the text element (CSS transform: scale(1)) and its container
  2. Do the calculation: containerWidth / unscaledWidth
  3. Set element scale to the result of the second step
  4. Set container height to match the height of scaled text

As a result we get perfectly fitted header 🙂

All we need to do is to wrap our header with some container to preserve space behind it, because CSS transform doesn’t  affect other elements positions.

In the stylesheet we need to set text-align for the container and display property for our header. transform-origin is set for the top-center of our header.

Last part is this little JS function. It uses my method, and it’s jQuery free 😉 You can have as many scalable headers on your page as you want. Just remember to place text inside proper container.

Here’s working example: https://codepen.io/maciejkorsan/full/BWLryj/


Having a nice project to code?

pawel@polarbits.co // +48 606 115 330