Body height 100% displaying vertical scrollbar
Remove the undesired vertical scrollbar on the body
height set to 100%
by resetting the default margin
and padding
of the browser:
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:
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:
Be careful though, as this could reduce content accessibility.
Flow and positioning
Avoid absolute positioning and maintain document flow instead. For center alignment:
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.
Was this article helpful?