CSS select first child if it's a certain tag

隐身守侯 提交于 2021-02-05 06:12:08

问题


I need to select a particular element only if it occurs as the first child of a div. Is there a CSS selector that'll handle that case?

For example, I want to select this figure:

<div>
    <figure></figure>
    <p></p>
    <p></p>
</div>

But I don't want to select this one:

<div>
    <p></p>    
    <figure></figure>
    <p></p>
</div>

I can't change the HTML, so I can't add a class. I know about the :first-child and :first-of-type selectors, but they don't fit this case by themselves. How can I select the first child only if it's a figure?


回答1:


figure:first-child will select all the figures that are first child of a parent.

Check this example at W3C.




回答2:


You could use CSS :first-child selector with descendant selector like this:

JSFiddle - DEMO

div figure:first-child {
    color:red;
}

OR: with CSS > child selector (as suggested by @Alohci)

DEMO

div > figure:first-child {
    color:red;
}



回答3:


I don't see any issue with figure:first-child selector. It would select the <figure> element only if it is the first child of its parent.

While :first-child represents any element which is the first child in the children tree of the parent, the figure part would limit the selector to match an element only if it is a <figure>.




回答4:


have you tried the following?

div figure {
    color: green;
}
div figure:first-child {
    color: blue;
}



回答5:


Use div figure:first-child selector.

Here is example

<div>
    <figure>test</figure>
    <p>div 1 pgraph1</p>
    <p>div 1 pgraph1</p>
</div>

<div>    
    <p>div 2 pgraph1</p>
    <figure>test 2</figure>
    <p>div 2 pgraph1</p>
</div>

CSS:

div figure:first-child{
    border:1px solid red;
}

It will apply red border only to first child.

Please refer to fiddle for demo



来源:https://stackoverflow.com/questions/26272820/css-select-first-child-if-its-a-certain-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!