Reputation: 93
Below is my HTML
<ul>
<li>title1
<ul>
<li>subtitle1.1</li>
<li>subtitle1.2</li>
</ul>
</li>
<li>title2
<ul>
<li>subtitle2.1</li>
<li>subtitle2.2</li>
</ul>
</li>
</ul>
And here is CSS
ul > li {
color: red;
}
I was expecting only title1
and title2
to be in red. But all sibling elements i.e subtitlle1.1
, subtitlle1.2
, subtitlle2.1
, subtitlle2.2
became red.
Child combinator should affect child only, but siblings here are inheriting top child's property. Could you please elaborate more on what is going behinf scene? And what css should look like if i want only title part above to be in red?
Upvotes: 1
Views: 400
Reputation: 43401
This is due to the fact that the color
property is inherited by default. So if you define a color on the top element (say <body>
) it will apply to all children that don't override this property. This is essential to the cascading mechanism central to CSS.
To solve your problem you can either :
First, wrap you text into a tag with (maybe add a class attribute) :
<ul>
<li><span class="term">title1</span>
...
</li>
...
</ul>
Then define the color :
ul > li > span,
ul .term {
color: red; # only apply to the span
}
<ul>
) is not really adapted. I'll recommend to use definition list (<dl>
).You can simply force the subtitle to use whatever color you want :
ul > li > ul > li {
color: black; # back to default document color
}
Upvotes: 1
Reputation: 9480
I would add a tag wrapper for the title and style it this way:
<ul>
<li><span>title1</span>
<ul>
<li>subtitle1.1</li>
<li>subtitle1.2</li>
</ul>
</li>
<li><span>title2</span>
<ul>
<li>subtitle2.1</li>
<li>subtitle2.2</li>
</ul>
</li>
</ul>
And you CSS in this case would be:
ul > li > span {
color: red;
}
This way only title1 and title2 would end up in red.
Upvotes: 0
Reputation: 700322
The style applies to the subtitles too, not because they are inside the outer list, but because they are immediate children of their own lists.
With the markup given, and no other information, there is no selector that can target only the first level of lists.
If you know that the list is inside another element, you can use the immediate child combinator to target the outer lists:
div > ul > li {
color: red;
}
You can override the style for the inner lists:
ul > li {
color: red;
}
ul > li > ul> li {
color: black;
}
If you can add an id or a class to the outer list, you can use that to target it, and it won't apply to the inner lists because they don't have that id or class:
.myList > li {
color: red;
}
Upvotes: 4