How to select the first element of a certain class with css selector

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>

step 1

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

  • .itemelements with class
  • is the first element of the parent element

That is to say, adding this sentence will not select any element, because divthe first element under the parent element is not class='.item'an element

In addition, you can use the sibling selector ~, which A~Bcan 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;
    }

step 2
Uncheck the unselected

.cont> .item ~ .item {
    
    
        color: #000;
    }

step 3

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 :notthe 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 classadd item_1this directly in it, use 2 It will be much faster classto select.item,.item_1

Guess you like

Origin blog.csdn.net/reol44/article/details/129855509