首页 > 解决方案 > 如果有多个图像,则添加样式

问题描述

我正在使用文本编辑器来创建<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%
}

但是如何选择第一个呢?

这是一个现场小提琴:http: //jsfiddle.net/zjwhgq81/14/

我需要一个在不同浏览器上的大多数浏览器都支持的 x-browser 兼容解决方案。

请不要建议向 中添加类或 id img,正如我提到的,我正在使用文本编辑器。

标签: javascripthtmlcss

解决方案


尝试这个:

选择一个孩子的帖子

.post p img:first-child:nth-last-child(1) {
    width: 100%;
}

选择有更多孩子的帖子

/* 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 -->


推荐阅读