簡體   English   中英

在多列布局中唯一的項目時如何居中

[英]how to center an item when it's the only one in a multi-column layout

我正在將動態圖像拖入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元素之后沒有高度,因為里面沒有靜態元素。 我也沒有找到清除它的明顯方法。 也許有人可以基於這個想法?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM