如何选择第一个img标签在一个div与许多img标签? [英] How to select first img tag in a div with many img tag?

查看:385
本文介绍了如何选择第一个img标签在一个div与许多img标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个html:

<div class="image">
   <img src=... />
   <img src= .../>
</div>

而我将css只应用于类图像的div的第一个图像,而不必添加class我的第一个img(在这种情况下,我会做 .image .img1 但是有另一种方式吗?

And I would to apply css only to the first image of div of class image without having to add a class to my first img (in that case, I would do .image .img1 but is there another way ?

非常感谢您的帮助

推荐答案

您可以使用:first-child

最后,更合适的方法是使用 :first-of-type

You could also use :nth-child(1) (where the 1 is = to the first child, 2 is equal to the second child etc.)

例如:

For example:

或:

Or:

或者(如果有其他元素,比如任何图片之前的< h1>

div.image img:nth-child(1) {}

Or (if there are other elements, say an <h1> that comes prior to any images: 

如果你有可能有一个div的类图像里面有图像,还有另一个div其中有图像,如下:

div img:first-of-type

HTML:



HTML:

<div class="image">
   <img src=... />
   <img src= .../>
   <div class="image">
      <img src=... />
      <img src= .../>
   </div>
</div>

然后使用这些选择器:

示例:

div.image > img:first-child {}

或:

div.image > img:nth-child(1) {}

或:

div > img:first-of-type

:first-child :nth-​​child():first-of-type 子组合器

请注意,:nth-​​child():first-of-type 是CSS3选择器,在使用IE时提供一些有限的支持。有关浏览器支持详情,请参见我可以使用CSS3选择器

Note that :nth-child() and :first-of-type are CSS3 selectors, which carry some limited support when using IE. See Can I use CSS3 Selectors for browser support details.

请考虑像 Selectivizr 这样的功能,以帮助标准化IE。

Consider something like Selectivizr to help standardize IE.

这篇关于如何选择第一个img标签在一个div与许多img标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆