Now there is a structure like this
How to use css to turn 'selected' into red
<div class="cont">
<p>不选中</p>
<p >不选中</p>
<h1>不选中</h1>
<p class="item">选中</p>
<p class="item">不选中</p>
<p>不选中</p>
<p class="item">不选中</p>
<p class="item">不选中</p>
<p class="item">不选中</p>
</div>
The first thing that comes to mind is the pseudo-class selector
.item:first-child
, but the above sentence actually selects elements that meet both conditions
.item
elements with class- is the first element of the parent element
That is to say, adding this sentence will not select any element, because
div
the first element under the parent element is notclass='.item'
an element
In addition, you can use the sibling selector
~
, whichA~B
can select all B elements after A, as long as they share a parent element,
Therefore, the first solution can be obtained
select all first.item
.cont> .item {
color: red;
}
Uncheck the unselected
.cont> .item ~ .item {
color: #000;
}
This is not very good, because the initial attributes have to be reset. If each
<p></p>
color is a different color set in a different place, it is not easy to change
At this time, you can use :not
the selector to get the second solution
.cont>.item:not(.item ~ .item){
color: red;
}
suggestion
- First, don’t use pseudo-class selectors, because mobile phones don’t seem to be able to use sibling selectors, and they won’t work if you put them on mobile phones
- Second, the readability is too poor, and if you want to select the second one, you need to use the sibling selector again, and so on for the third one, it will be very long to write, it is better to
class
additem_1
this directly in it, use 2 It will be much fasterclass
to select.item,.item_1