Reputation: 1878
I am still learning CSS and web development in general and have a basic understanding of how to create things with HTML/CSS. When looking around other peoples code/templates I often found this sort of structure in the CSS:
.grandparent .parent .child {
some: style;
}
My understanding is that this applies to elements with class child
AND has the parent class parent
AND has the grandparent class grandparent
. Like this:
<div class="grandparent">
<div class="parent">
<div class="child">
Some text
</div>
</div>
</div>
And the style would NOT apply if the structure was something like this:
<div class="grandparent">
<div class="some-other-class">
<div class="child">
Some text
</div>
</div>
</div>
However, often I find that there is only one instance of the class child
in the entire HTML document and to me it therefore seems unnecessary to declare it in the CSS with parents and grandparents and you could instead just write:
.child {
some: style;
}
My questions are:
Upvotes: 1
Views: 106
Reputation: 7229
Using the class names before the .child
class name makes the selector more specific. More specific selectors will overwrite less specific selectors.
For example:
All .child
elements will have the red color, except the one with the parent element with the class option-green
because there is a more specific selector for that case.
.child {
color: red;
}
.option-green .child {
color: green;
}
<ul>
<li>
<div class="child">Option 1</div>
</li>
<li>
<div class="child">Option 2</div>
</li>
<li>
<div class="child">Option 3</div>
</li>
<li class="option-green">
<div class="child">Option 4</div>
</li>
<li>
<div class="child">Option 5</div>
</li>
</ul>
Answers to your questions:
Also note that it isn't necessary that the specific parent needs the class name. For example, the following .child
element will also have the green color set:
<div class="option-green">
<div>
<div><i><span class="child">I'm green!</span></i></div>
</div>
</div>
Upvotes: 3