Home > Mobile >  Margin property not working with :root selector
Margin property not working with :root selector

Time:08-16

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 >Lorem.</p>
  <p >Lorem ipsum</p>
  <p >Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, saepe animi? </p>
  <p >1$</p>
  <button>Buy</button>
</body>

</html>

CodePudding user response:

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; }

CodePudding user response:

Consider to add a CSS normalize or a CSS reset, here an interesting link

CodePudding user response:

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;
}

CodePudding user response:

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!

  • Related