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 >
<div >
<div >
Some text
</div>
</div>
</div>
And the style would NOT apply if the structure was something like this:
<div >
<div >
<div >
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:
- Is there any performance gains from doing it either way?
- Is that just how you are supposed to declare CSS classes from a semantic point of view?
- Did I just find people who write unneccesary long CSS declarations?
CodePudding user response:
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 >Option 1</div>
</li>
<li>
<div >Option 2</div>
</li>
<li>
<div >Option 3</div>
</li>
<li >
<div >Option 4</div>
</li>
<li>
<div >Option 5</div>
</li>
</ul>
Answers to your questions:
- having less nested selector will be quicker of course.
- start with simple selectors first and make them more specific when needed.
- can be, sometimes people change code and forgot to update the CSS for example.
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 >
<div>
<div><i><span >I'm green!</span></i></div>
</div>
</div>