Home > Net >  CSS multiple classes on the same row in the stylesheet
CSS multiple classes on the same row in the stylesheet

Time:01-05

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:

  1. Is there any performance gains from doing it either way?
  2. Is that just how you are supposed to declare CSS classes from a semantic point of view?
  3. 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:

  1. having less nested selector will be quicker of course.
  2. start with simple selectors first and make them more specific when needed.
  3. 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> 
  • Related