15

我有这个 html:

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

而且我只想将css应用于类图像的div的第一个图像,而不必向我的第一个img添加一个类(在这种情况下,我会这样做,.image .img1但还有其他方法吗?

非常感谢你的帮助

4

5 回答 5

36

您可以使用:first-child选择器来执行此操作。

您也可以使用:nth-child(1) (其中 1 是 = 第一个孩子,2 等于第二个孩子等)

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

例如:

div.image img:first-child {}

或者:

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

或者(如果有其他元素,说一个<h1>在任何图像之前的元素:

div img:first-of-type

如果您有可能拥有一个带有类图像的 div,其中包含图像,并且还有另一个包含图像的 div,如下所示:

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-typechild combinator的文档。

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

考虑像Selectivizr这样的东西来帮助标准化 IE。

于 2013-03-22T14:50:26.460 回答
6

您可以使用first-child选择器来做到这一点

.image img:first-child
{
  height:500px;
  width:200px;
  border:15px solid Red;    
}

JS 小提琴示例

于 2013-03-22T14:46:23.900 回答
4

':first-child' 选择器似乎是您需要的。

http://www.w3schools.com/cssref/sel_firstchild.asp

于 2013-03-22T14:46:11.130 回答
2

如果您想要 DIV 中的第一个图像(并且可能在它之前有其他元素),您需要first-of-type而不是first-child

div > img:first-of-type {}

考虑以下html

<div>
    <p>paragraph, this is :first-child</p>
    <img src="..."><!-- this is img:first-of-type -->
</div>

更多细节可以在https://developer.mozilla.org/en-US/docs/CSS/:first-of-type找到

于 2013-03-22T14:59:29.680 回答
2

article>img:first-child {
   border:1px solid #f00;
}
<article class="image">
   <img src=... />
   <img src= .../>
   <div class="image">
      <img src=... />
      <img src= .../>
      <img src= .../>
            
   </div>
   <img src= .../>
      <img src= .../>
</div>

于 2019-01-01T02:45:17.513 回答