【问题标题】:how to center an item when it's the only one in a multi-column layout当它是多列布局中唯一的一个项目时如何居中
【发布时间】:2017-08-25 04:31:45
【问题描述】:

我将动态图像拉入 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 列布局中定位 last 项,如果它是其行中的唯一项,我现在使用这个:

p>img:nth-child(odd):last-of-type{
  column-span: all;
  margin: auto;
  width: 50%;
}

【问题讨论】:

  • 添加您的标记

标签: html css css-multicolumn-layout


【解决方案1】:

您的标记和 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 元素之后没有高度,因为它里面没有任何东西是静态的。我也没有看到明显的方法来清除它。也许有人可以基于这个想法?

【讨论】:

  • 对列数有什么影响?
  • 你能解释一下关于 OP 的 psot 到底发生了什么
  • Eric,请参阅我更新的帖子,其中包含您的答案。使用 column-span 很优雅,而且似乎可以解决问题!
猜你喜欢
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 2022-08-12
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 2013-09-20
  • 1970-01-01
相关资源
最近更新 更多