我正在将动态图像拉入 2 列布局中。如果只有一张图像,我该如何将其居中,或将各列折叠成一个?目前,单个图像放置在左列中。有没有纯 CSS 的解决方案?
如果一列中的最后一项是该行中的唯一一项,相同的逻辑是否适用于该列中的最后一项?
p{
column-count: 2;
column-gap: 0;
}
p>img{
display: block;
width: 100%;
height: auto;
border: 3px solid transparent;
box-sizing: border-box;
}
感谢 Eric N 的回答和column-span,以下添加的 CSS 使 2 列布局中的第一个也是唯一的元素居中:
p>img:first-of-type:last-of-type{
column-span: all;
margin: auto;
width: 50%;
}
此外,为了定位 2 列布局中的最后元素,如果它是其行中唯一的元素,我现在使用这个:
p>img:nth-child(odd):last-of-type{
column-span: all;
margin: auto;
width: 50%;
}
最佳答案
你的标记和CSS会有很大帮助。如果没有它,您可能只能通过使用来定位单个元素:
img:first-of-type:last-of-type {
/* centering styles */
}
编辑:
看到 CSS 后,这变得非常棘手。我想出了这个令人畏惧的黑客:
p>img:first-of-type:last-of-type {
position: absolute;
left: 50%;
width: 50%;
transform:translateX(-50%);
}
这完成了工作...除了 p 元素之后没有高度,因为它里面没有静态的东西。我也没有看到明显的方法来清除它。也许有人可以基于这个想法?
关于html - 当一个元素是多列布局中唯一的一个元素时,如何将其居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40921259/