DEV Community

Kevin J. Estevez
Kevin J. Estevez

Posted on

The font-size trick in layouts

Have you ever faced the issue when 50% and 50% does not fit in 100%? 🤯 Where has the math gone?

I remember my first days learning CSS, putting markup tags here and there then styling them out! yeah! the least aesthetic page ever xD

Flexbox had just appeared and then barely used, we still fought aligning items with float: left and float: right and the famously used clear: both

Nothing worse than dealing with those properties and then boom! we played the fools trying to split a view evenly in two pieces 50/50 using display: inline-block and width: 50% ending with something like this:

HTML

<div class="container">
  <div class="item">
    item 1
  </div>
  <div class="item">
    item 2
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

.container {
  width: 100%;
}

.item {
  display: inline-block;
  width: 50%;
}
Enter fullscreen mode Exit fullscreen mode

Fooling!

And you know the end, how 50% plus 50% is different than 100%? then more than one ended doing the weirdest thing ever done 50% and 49% 🤦🏻‍♂️ others tried to heal the wound a bit by evenly distributing the difference like 49.5% and 49.5%

But you know what? just to make it worse guess what? That's not gonna behave as well as expected if you're aiming for responsive views

Problem solved!

Do you know what's the real issue here?

Well it's even simpler than you thought! The reason why 50/50 doesn't fit 100 is because of the font-size yeah!

Remember we're using display: inline-block right? to change the default block value of divs, and as fact in CSS all the inline elements by default share a property called font-size.

Wait! divs could have font-size? for sure they can once you change their display property from block to inline, even inline-block

Conclusion

If you do not set a font-size property to your 50/50 elements they will inherit from their parent (which most of the time might not be zero)

All you have to do is set font-size: 0; to your items and boom! out of magic everything will work! Here's an example of the result so you could check it out:

Before you go!

Note: The example above it's working pretty well just because we don't have content inside those divs, once you have some content there by default most of the browsers set the property box-sizing: content-box; and I'd suggest you to set that property to box-sizing: border-box;.

Thanks for reading and see you soon... 🤗

Top comments (0)