I recently wrote some CSS code to remove default browser styles:
/* Box sizing rules */
*,
*::before,
*::after {
box-sizing: border-box;
}
/* Remove default padding */
ul[class],
ol[class] {
padding: 0;
}
/* Remove default margin */
body,
h1,
h2,
h3,
h4,
p,
ul[class],
ol[class],
li,
figure,
figcaption,
blockquote,
dl,
dd {
margin: 0;
}
/* Set core body defaults */
body {
min-height: 100vh;
scroll-behavior: smooth;
text-rendering: optimizeSpeed;
line-height: 1.5;
}
/* Remove list styles on ul, ol elements with a class attribute */
ul[class],
ol[class] {
list-style: none;
}
Despite this code, I noticed that when viewing my HTML file in Google Chrome and inspecting the body element, the default margin was still displaying. The code I expected to see for the body was:
body {
display: block;
margin: 0;
}
I'm puzzled as to why the default values are taking precedence over my CSS. Even though I haven't targeted the body selector anywhere else in my stylesheet, the user agent stylesheet seems to override it. Strangely, this issue only seems to affect the body element; other elements like h1 or ul[class] correctly reflect my CSS changes.
One workaround has been to add a specific class or ID to the body and set the margin to 0 within that identifier. However, this feels like a messy solution. Are there any better ways to resolve this conflict?