javascript - 如果有多个图像,请添加样式

标签 javascript html css

我正在为创建 <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/

相关文章:

javascript图像调整窗口大小

javascript - Ajax 不通过 POST 向 PHP 发送变量

css - 如何在 css 的不透明环境中使用粗体文本?

javascript - 根据值更改 <td> <i> CSS

javascript - CSS 背景位置随页面大小调整而移动

javascript - 数据表中的事件监听器拒绝工作

javascript - 如何使用两个不同的 ui 路由器在 angularjs 中的状态之间共享范围数据?

javascript - 设置 NumbroJS 文化

javascript - 在 html5 中旋转嵌入的 pdf

javascript - 用于大型 html 的 DOMParser