How to Remove Default Margin and Padding in CSS Quickly
To remove default margin and padding in CSS, use the universal selector
* with margin: 0; and padding: 0;. This resets all elements to have no space around them by default.Syntax
The universal selector * targets all HTML elements. Setting margin: 0; removes all default outer space, and padding: 0; removes all default inner space inside elements.
css
* {
margin: 0;
padding: 0;
}Example
This example shows how to remove default margin and padding from all elements, so the page content starts with no extra space around it.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Remove Default Margin and Padding</title> <style> * { margin: 0; padding: 0; } body { font-family: Arial, sans-serif; } h1 { background-color: lightblue; } p { background-color: lightgray; } </style> </head> <body> <h1>Heading with No Margin</h1> <p>Paragraph with no padding or margin.</p> </body> </html>
Output
A webpage with a blue heading and gray paragraph touching the edges of the browser window with no space around them.
Common Pitfalls
Sometimes developers forget to reset both margin and padding, which leaves unwanted space. Also, using * selector affects all elements and can impact performance on large pages. Another mistake is not adding box-sizing: border-box; which helps with sizing when padding is added later.
css
/* Wrong: only margin reset */ * { margin: 0; } /* Right: reset both margin and padding and add box-sizing */ * { margin: 0; padding: 0; box-sizing: border-box; }
Quick Reference
| Property | Purpose | Example Value |
|---|---|---|
| margin | Removes outer space around elements | 0 |
| padding | Removes inner space inside elements | 0 |
| * | Universal selector targets all elements | N/A |
| box-sizing | Includes padding and border in element's total width | border-box |
Key Takeaways
Use the universal selector * with margin: 0 and padding: 0 to remove default spaces.
Resetting both margin and padding ensures consistent layout across browsers.
Add box-sizing: border-box for easier sizing when adding padding later.
Be mindful that * selector affects all elements and may impact performance on large pages.
Always test your reset styles in different browsers for consistent results.