如何在CSS中定位div的特定<img>元素?

Net*_*110 9 html css

我有一些像这样的代码:

<div id="foo">
 <img src="bar.png" align="right">
 <img src="cat.png" align="right"> 
</div>
Run Code Online (Sandbox Code Playgroud)

现在我的问题是如何在使用上述代码时在CSS中定位特定图像?

Dav*_*mas 14

这完全取决于您想要定位的图像.假设它是第一个(虽然实现两者都相似)图像:

#foo img[src="bar.png"] {
    /* css */
}


#foo img[src^="bar.png"] {
    /* css */
}

#foo img:first-child {
    /* css */
}

#foo img:nth-of-type(1) {
    /* css */
}
Run Code Online (Sandbox Code Playgroud)

参考文献:


cha*_*ers 13

您可以向图像OR添加类

.foo img:nth-child(2) { css here }
Run Code Online (Sandbox Code Playgroud)

要么

.foo img:first-child { css here }
.foo img:last-child { css here }
Run Code Online (Sandbox Code Playgroud)


Har*_*ker 11

我不知道为什么每个人都固定在#foo div上.你可以定位img标签,甚至不用担心div标签.这些属性选择器由"开头"选择.

img[src^=bar] { css }
img[src^=cat] { css }
Run Code Online (Sandbox Code Playgroud)

这些选择"包含".

img[src*="bar"] { css }
img[src*="cat"] { css }
Run Code Online (Sandbox Code Playgroud)

或者你可以选择确切的src.

img[src="bar.png"] { css }
img[src="cat.png"] { css }
Run Code Online (Sandbox Code Playgroud)

如果你想要同时定位它们,那么你可以使用div id.

#foo img { css }
Run Code Online (Sandbox Code Playgroud)

对于其中一个图像,根本不需要担心#foo div.