0

I have used the :root selector to apply a margin to all the elements on the page; while the color and font-family properties work,the margin property doesn't. Am i making a mistake?

I have refered to the following site https://www.digitalocean.com/community/tutorials/css-root-pseudo-class on using the :root CSS selector and in the examples it verifies the usage of a margin property.

:root {
  margin: 0;
  color: red;
  font-family: Arial;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <p class="new">Lorem.</p>
  <p class="title">Lorem ipsum</p>
  <p class="desc">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, saepe animi? </p>
  <p class="price">1$</p>
  <button>Buy</button>
</body>

</html>

3 Answers3

0

Your rules are being applied as intended, it's just that the body element defaults to a margin of 8px. The html tag is your root element here so it's not being overridden.

Try

:root {
  color: red;
  font-family: Arial;
}

:root body { 
  margin: 0;
}
Alex
  • 848
  • 6
  • 7
0

You can do something like this:

:root *{
  margin: 0;
  color: red;
  font-family: Arial;
}

Or even simpler

*{
  margin: 0;
  color: red;
  font-family: Arial;
}

"*" selects all elements on the page. I hope this helps!

Astw41
  • 394
  • 3
  • 12
0

while the color and font-family properties work,the margin property doesn't

color and font-family are inherited properties.

margin is not an inherited property.

If you want to set the margin of all elements on a page to 0 (which is probably a bad idea), use the universal selector *:

* { margin: 0; }
connexo
  • 53,704
  • 14
  • 91
  • 128
  • Thanks a lot! Although i would like to ask why adding a margin of 0 is a bad idea? I am learning by my self and i ask for your advice. – Sketchy potatoman Aug 16 '22 at 10:27
  • 1
    @Sketchypotatoman - Think about paragraphs printed in a book. There's a vertical space between each paragraph which makes the book easier to read, right? By default, when you use a `

    ` element in your HTML, you'll get that same vertical spacing for free, because `

    ` elements have default margins. When you assign `margin:0` to everything, you lose that "for free" behaviour. Similar applies to a number of other elements.

    – Alohci Aug 16 '22 at 13:27