Web browsers like Google Chrome and Mozilla Firefox apply a few default CSS styles to every HTML element. These are called user agent stylesheets.
Typically, the user agent stylesheets apply paddings and margins to ensure that elements have proper spacing and formatting in the absence of custom CSS rules.
For example, Microsoft Edge uses a default value of 8px margin on the body selector.
Developers override these default browser styles via user-defined CSS stylesheets to achieve a consistent look on all browsers and devices.
In this short bonus article, you'll learn how to fully reset CSS margins and paddings in your website or web application.
Reset CSS Padding and Margin of the Document Body
To reset the margins and padding on the HTML body element, open your website's global CSS file and add the following properties to the body
selector.
body {
margin: 0;
padding: 0;
}
This code snippet sets all four margin and padding properties (top, right, bottom, and left) to zero (0
). Now, pesky whitespaces around the direct children of the body element won't throw off your website's layout anymore.
Here's a practical demonstration for you.
In the screenshot above, I've removed the margin: 0;
property from the body tag of this blog's home page. Notice the whitespaces above the navigation bar? That's what the browser applies to every webpage by default unless overridden.
The Universal Selector CSS Reset Method
To reset the margins and padding of the entire website, use the global/Universal CSS selector (*
) like the following.
* {
margin: 0;
padding: 0;
}
This way, you remove browser-applied margins and paddings from every single element (E.g., <ul>
, <li>
, <figure>
, <blockquote>
, etc.)
Also, use the box-sizing: border-box;
property in the global selector to ensure the browser includes the paddings and borders in the total width and height of the elements.
Wrapping Up
And that's it! Now you know the basics of how to reset CSS margins and paddings. I hope you found this short article helpful.
But in case you're curious to learn more about CSS margins and paddings, check out my CSS Margin vs Padding vs Gap - The Ultimate Guide.