javascript - 如果有多个图像,则添加样式
问题描述
我正在使用文本编辑器来创建<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
,正如我提到的,我正在使用文本编辑器。
解决方案
尝试这个:
选择一个孩子的帖子
.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 -->
推荐阅读
- javascript - react-hook-form:handleSubmit 不是函数
- c# - 在 C# 中使用 Selenium 添加功能的正确方法是什么?
- reactjs - 如何在 Reactjs 中使用上下文提供者和消费者?
- css - 我怎样才能将“调整大小手柄”绝对定位在另一个具有位置粘性的元素之上?
- azure - Xamarin 表单中的 Azure AD B2C
- c - 使用 valgrind 时出现“断言‘iFuncWrapper’失败”
- php - Laravel PHP - 在字符串中使用路由参数
- c++ - 将2个大数相乘并将其存储在一个长变量中,但会发生溢出
- excel - 邮件合并到 MS Word 中的表格中
- python - 基于组内的对进行过滤 - 如果值表示在末尾