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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10036243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:35:49  来源:igfitidea点击:

How to target a specific <img> element of a div in CSS?

htmlcss

提问by Netizen110

I've a code of some what like this:

我有一些这样的代码:

<div id="foo">
 <img src="bar.png" align="right">
 <img src="cat.png" align="right"> 
</div>

Now my question is how do I target a specific image in CSS when having the above code?

现在我的问题是,当我拥有上述代码时,如何在 CSS 中定位特定图像?

回答by David says reinstate Monica

It depends entirely upon which image you want to target. Assuming it's the first (though the implementations are similar for both) image:

这完全取决于您要定位的图像。假设它是第一个(尽管两者的实现相似)图像:

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


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

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

#foo img:nth-of-type(1) {
    /* css */
}

References:

参考:

回答by chadpeppers

You can add a class to the images OR

您可以为图像添加一个类或

.foo img:nth-child(2) { css here }

or

或者

.foo img:first-child { css here }
.foo img:last-child { css here }

回答by Harry The Mad Lurker

I don't know why everyone is so fixed on the #foo div. You can target the img tag and not even worry about the div tag. These attribute selectors select by the "begins with".

我不知道为什么每个人都如此执着于#foo div。您可以定位 img 标签,甚至不用担心 div 标签。这些属性选择器由“开始于”选择。

img[src^=bar] { css }
img[src^=cat] { css }

These select by "contains".

这些选择“包含”。

img[src*="bar"] { css }
img[src*="cat"] { css }

Or you can select by the exact src.

或者您可以通过确切的 src 进行选择。

img[src="bar.png"] { css }
img[src="cat.png"] { css }

If you want to target them both, then you could use the div id.

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

#foo img { css }

For just one of the images, there is no need to worry about the #foo div at all.

对于其中一张图像,根本无需担心 #foo div。

回答by Niet the Dark Absol

div > img:first-child {/*the first image*/}
div > img:last-child {/*the last image*/}

That should do it.

那应该这样做。

回答by Andres Riofrio

All of the following solutions only work in recent browsers.

以下所有解决方案仅适用于最近的浏览器。

You can select by child position:

您可以按子位置选择:

 #foo img:first-child { /* for the bar */ }
 #foo img:nth-child(2) { /* for the cat */ }

You can select by child position, counting only images:

您可以按子位置选择,仅计算图像:

 #foo img:first-of-type { /* for the bar */ }
 #foo img:nth-of-type(2) { /* for the cat */ }

You can select by image URL:

您可以通过图片网址选择:

 #foo img[src^=bar] { /* for the bar */ }
 #foo img[src^=cat] { /* for the cat */ }

回答by Marat Tanalin

#foo > IMG:first-child {/* first of two IMGs */}
#foo > IMG + IMG       {/* second one */}

Works in all browsers including IE7+.

适用于所有浏览器,包括 IE7+。