Reputation: 85
Is there any difference between applying CSS to body tag and universal selector (*). Which scenario will take precedence while applying specificity rules.
Upvotes: 1
Views: 847
Reputation: 10602
As other's have pointed out *
searches for all elements. In short, anytime you specify a specific tag, the tag will naturally target it's own environment. However, another reason is because the html
selector is considered the root of any document and the body
is a descendant. So * {}
!== all elements in html, body {}
Therefore, as you inquired, *
does not equal <body>
. Furthermore, what's even more interesting is that :root
and html
both target the same thing, except that :root
has a higher priority over it's html
counterpart.
See HTML spec There are only 2 elements that descend from the HTML
root <head>
and <body>
. See body spec
Here is a short snippet to help visualize:
* {
background-color: green;
}
body {
background-color: blue;
}
:root {
/* i have higher priority over html {} */
background-color: pink;
}
html {
background: purple;
}
<p>
test
</p>
<div>
test2
</div>
<footer>
Copyright © 2018
</footer>
Upvotes: 0
Reputation: 2277
Applying styles with the universal selector will apply the code to every element
Applying styles to the body will only affect the body but other elements may inherit those styles
The specificity of the Universal Selector is the lowest you can use. More info on this can be found in the W3C docs
Upvotes: 3
Reputation: 1457
Let's take this example:
body{
background-color: red;
}
.random-class{
background-color: green;
}
.second-random-class{
font-size: 15px;
}
is not the same as
* {
background-color: red
}
.random-class{
background-color: green;
}
.second-random-class{
font-size: 15px;
}
since the *
selector will apply the background-color
to EVERY element.
The *
-selector with background-color: red
will result in
body{
background-color: red;
}
.random-class{
background-color: green;
}
.second-random-class{
font-size: 15px;
background-color: red; // <-- received this from *
}
Note that this will NEVER appear like this in the source code (at least if you are not using SCSS or LESS or a similar preprocessor). This is just how the hierachy is defined.
Upvotes: 0
Reputation: 51
The selector (*)
is used for all elements of the page (head, body ...). However, if you apply the body tag, only the body elements have been modified.
Upvotes: 0
Reputation: 77
body is for body and (*
) is for (*
) ? x)
If some code ( i hope not) is not in the body, the CSS still apply :)
Upvotes: 0