Explain Codes LogoExplain Codes Logo

Body height 100% displaying vertical scrollbar

html
responsive-design
css
best-practices
Alex KataevbyAlex Kataev·Jan 30, 2025
TLDR

Remove the undesired vertical scrollbar on the body height set to 100% by resetting the default margin and padding of the browser:

* { margin: 0; /* Margin? There's no margin for error here. */ padding: 0; /* Padding? We're not packing for a trip. */ } html, body { height: 100%; overflow: auto; /* Enables scroll if content demands it */ }

The CSS above applies a universal selector * to reset margins and padding for elements, thus preventing scrollbar triggering due to hidden overflow. The rule overflow: auto; on the body only allows scrolling if the content overflows the screen, making the scrollbar a context-aware element instead of a persistent visual clutter.

Decoding the margin collapse

Margin collapse is a CSS phenomenon where adjacent vertical margins combine to form a single margin equal to the greatest individual margin. This seemingly innocuous behavior can cause shift in content and potentially introduce unexpected scrollbar appearance, as it doesn't add to the height dimensions.

Mastering height with calc

The CSS function calc() allows precise adjustment of element height, keeping in mind the margins. Set your #container's height with a correct offset:

#container { height: calc(100% - 20px); /* Assume we have a 20px margin, because assuming makes an "ass" of "u" and "me" */ }

This results in your container fitting within the body without causing overflow due to margins.

The art of resetting

Resetting CSS helps avoid unexpected layout surprises. Here's how one can do it:

  • Normalize.css can help establish cross-browser consistency.
  • Using a universal selector, you can erase default margins and paddings across all elements.
  • You could also individually neutralize default margins and paddings on particular elements needing specific styles.

Controlling overflow

Sometimes, you might want some elements to slide off the viewport without causing a scrollbar. Here's how you manage it:

.overflow-hidden { overflow: hidden; /* Overflow? More like "over and out!" */ }

Be careful though, as this could reduce content accessibility.

Flow and positioning

Avoid absolute positioning and maintain document flow instead. For center alignment:

.centered-container { margin-left: auto; margin-right: auto; width: 50%; /* Just like my coffee cup, half full or half empty? */ }

Effectively manage the float property to avoid layout disruption, and zero out margins and padding to avoid float-induced unexpected behaviors.

Browser compatibility checks

Remember that older browsers may not support calc(). Do check Can I use to verify its compatibility with your target browsers.