我想将css应用于第一张图片

时间:2012-02-14 18:56:20

标签: css

我试过了first-child,但我无法让它发挥作用。

CSS

.post_locked2 img:first-child {

HTML

<div class="post_locked2">
  <h1>title...
  <h2>Subtitle....
  <p>.....
  <p>....
  <img class="aligncenter" src="http://www.what...
  <img title="RockDizFile" src="http://......
  <img title="Bullet" src="http://wwww.......
</div>

您如何仅将css应用于第一张图片?

2 个答案:

答案 0 :(得分:10)

:first-child仅选择父元素的第一个子元素。在OP中,示例:first-child将是h1,因此img:first-child实际上不会选择任何内容。

请改用nth-of-type(1) http://reference.sitepoint.com/css/pseudoclass-nthoftype

<!-- in the head -->
<style>
.post_locked2 img:nth-of-type(1){
  border:5px solid red;
}
</style>

<!-- in the body -->
<div class="post_locked2">
<img class="aligncenter" src="http://www.what...
<img title="RockDizFile" src="http://......
<img title="Bullet" src="http://wwww.......
</div>

这是另一个使用它的例子:http://jsfiddle.net/FsEhD/

答案 1 :(得分:0)

你试过这个吗?

post_locked2>.aligncenter:first-child {some:styles;}

post_locked2>img:first-child {some:styles;}