我正在为创建 <p>
的帖子使用文本编辑器对于每个部分的内容。
有时内容包含 1 张或更多图片,有时不包含图片。
.post{
background-color: #000;
margin-bottom: 20px;
color: #fff
}
.post img + img{
width: 50%
}
<div class="post">
<p>First Post</p>
<p>
<img src="http://placehold.it/300x300/200">
</p>
</div> <!-- .post -->
<div class="post">
<p>Second Post</p>
<p>
<img src="http://placehold.it/300x300/200">
<img src="http://placehold.it/300x300/200">
</p>
</div> <!-- .post -->
所以如果有两张图片,我希望每张都拍摄 50%
的宽度。
我可以设置第二张图片的宽度:
.posts img + img{
width:50%
}
但是如何选择第一个呢?
这是一个现场 fiddle : http://jsfiddle.net/zjwhgq81/14/
我需要一个 x 浏览器兼容的解决方案,该解决方案在不同浏览器上的大多数浏览器中都受支持。
请不要建议向 img
添加类或 ID ,正如我提到的,我正在使用文本编辑器。
最佳答案
试试这个:
选择一个 child 的帖子
.post p img:first-child:nth-last-child(1) {
width: 100%;
}
选择有更多 child 的帖子
/* Select the first of more */
.post p img:nth-child(1) {
width:60%
}
/* Select others of more except the first */
.post p img:nth-child(n+2) {
width: 10%;
}
.post{
background-color: #000;
margin-bottom: 20px;
color: #fff;
width:100%;
}
.post p img:first-child:nth-last-child(1) {
width: 100%;
}
.post p img:nth-child(1) {
width:60%
}
.post p img:nth-child(n+2) {
width: 10%;
}
<div class="post">
<p>First Post</p>
<p>
<img src="http://placehold.it/300x300/200">
</p>
</div> <!-- .post -->
<div class="post">
<p>Second Post</p>
<p>
<img src="http://placehold.it/300x300/200">
<img src="http://placehold.it/300x300/200">
</p>
</div> <!-- .post -->
关于javascript - 如果有多个图像,请添加样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51957276/