Is there a difference between .class element
and element.class
in a CSS selector?
I had always been shown element.class
but j
element.class
selects all <element />
s with that class. .class element
selects all <element />
s that are descendants of elements that have that class.
For example, HTML:
<div class='wrapper'>
<div class='content'></div>
<div></div>
<div class='footer'></div>
</div>
For example, CSS:
div.wrapper {
background-color: white; /* the div with wrapper class will be white */
}
.wrapper div {
background-color: red; /* all 3 child divs of wrapper will be red */
}
"element.class" selects elements that have the given class.
".class element" selects all elements that are children of anything with the given class.
Example:
<div class="foo">
<p>...</p>
</div>
div.foo
would select the div, while .foo p
would select the child paragraph. It should be noted that without specifying direct child via the ">" selector, this will traverse the entire document tree when looking for children.
I like to think it as follows:
1) a, b = a OR b
2) a b = a AND b (on that order)
3) a.b = a.b (on that order)
2, 3) a b is not the same as b a.
2) Elements belonging to a and b simultaneously, i.e. nor a or b elements. Is a range selection.
3) a elements of b class. Is an exact selection.
very simple example:
HTML:
<ul class="a">
<li>1</li>
<li class="a">2</li>
<li>3</li>
</ul>
CSS:
.a li{color:blue;}
li.a{color:red;}