[DOUBT] Selecting Nested element in CSS


#1

Hey, I was wondering if selecting this piece of html:

<ul class='main-list'>
  <li> ... </li>
  <li> ... </li>
  <li> ... </li>
</ul>```

as this in CSS:

.main-list li {

}


or as this:

li {

}


Would it make a big difference in my code?

#2

Yes, quite a lot.

li is a type selector that will match all list items.

.main-list is a class selector which will only match that element and its children.

Eg. 1.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>type vs class</title>
<style>
body {
  font-size: 100%;
}
.main-list {
  color: red;
  background: teal;
}
li {
  color: yellow;
}
h1,
h2,
h3 {
  font-size: 1em;
}
</style>
</head>
<body>
<div>
<ul>
  <li><h1>Main List</h1></li>
  <li><ul class="main-list">
    <li><h2>Child List</h2></li>
    <li><ul>
    <li><h3>Grandchild List</h3></li>
      <li>Aa..Zz</li>
      <li>0..n</li>
      <li>T-F</li>
    </ul></li>
    <li><ul>
    <li><h3>Grandchild List</h3></li>
      <li>Aa..Zz</li>
      <li>0..n</li>
      <li>T-F</li>
    </ul></li>
  </ul></li>
  <li><ul>
    <li><h2>Child List</h2></li>
    <li><ul>
    <li><h3>Grandchild List</h3></li>
      <li>Aa..Zz</li>
      <li>0..n</li>
      <li>T-F</li>
    </ul></li>
    <li><ul>
    <li><h3>Grandchild List</h3></li>
      <li>Aa..Zz</li>
      <li>0..n</li>
      <li>T-F</li>
    </ul></li>
  </ul></li>
  <li><ul>
    <li><h2>Child List</h2></li>
    <li><ul>
    <li><h3>Grandchild List</h3></li>
      <li>Aa..Zz</li>
      <li>0..n</li>
      <li>T-F</li>
    </ul></li>
    <li><ul>
    <li><h3>Grandchild List</h3></li>
      <li>Aa..Zz</li>
      <li>0..n</li>
      <li>T-F</li>
    </ul></li>
  </ul></li>
</ul>
</div>
</body>
</html>

Save the above HTML as, ‘eg_1.html’ in a folder named, ‘selectors’ so other examples may be saved later.

Once you have saved it, launch it in a browser. Note how the style rules were applied. Avoid drawing any conclusions. There is more to this than can be expressed in black and white, even while it is declarative. We need to peel away the layers and form an idea of causes and effects.

What do we know?

Well, we know that a class selector has higher specificity (importance) than a type selector. But that does not explain why we have yellow text everywhere, and no red, not even in the class named element.

Why is the teal background only in the first segment, and none of the others?

I won’t attempt to get into the details, just yet, until you have reached this point and are ready to proceed further with examination of this, and subsequent examples.


[Edit]

If you have copied and saved the earlier code already, give it a new name, like ‘eg__1.html’ and copy/save the above revised code for a clearer demonstration. Nothing has changed in the general discussion.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.