简体   繁体   中英

CSS :selector doesn't work with different tags?

Say I have

<div class="myClass">
   <div class="child"></div>
   <span class="child"></span>
   <a class="child"></a>
</div>

If I use

.child:first-of-type { /* Code here */ }

Then all three tags get the CSS code since they are all of different types. Is there a way of still using this selector but with different tags?

只需将标签添加到选择器,例如

div.child:first-of-type { /* Code here */ }

From docs:

Pseudo-class :first-of-type

The :first-of-type pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element. Same as :nth-of-type(1) .

Syntax

selector:first-of-type{ properties }

demo

first-of-type selects as its type but you have defined every child with different types. In the demo I have provided there are two more div (of-type) added in which first div is being selected and another (of-type) is span which is only one so it is selecting if you add more span then it doesn't select other span.

In your case, if you want to select only first then apply :first-child

The :first-of-type CSS pseudo-class represents the first sibling of its type in the list of children of its parent element. source

Example taken from MDN provide the source above

div :first-of-type {
  /*background-color: lime;*/
  font-weight: bold;
}


<div>
  <span>This span is first!</span>
  <span>This span is not. :(</span>
  <span>what about this <em>nested element</em>?</span>
  <strike>This is another type</strike>
  <span>Sadly, this one is not...</span>
</div>

Result:

This span is first! This span is not. :( what about this nested element ? This is another type Sadly, this one is not...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM