2017-06-06 23 views
1

我知道flexbox爲居中物品提供了一個很好的解決方案。但是當我有3件物品時,我遇到了一個問題,並且我希望中心(第2)物品相對於窗口居中,而與其他2件物品的大小無關。當它的兄弟姐妹擁有不同的寬度時,將一個彈性項目居中

在筆中,您可以看到第二項「客戶端索引」偏離中心,因爲右側的內容大於左側的內容。 我該如何強制它自己居中?

.flex { 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: space-between; 
 
}
<div class="flex"> 
 
    <span style="font-size:12px;">small</span> 
 
    <span style="font-size:20px;">Client Index</span> 
 
    <span style="font-size:18px;">Lots of content that moves the center</span> 
 
</div>

My Codepen

回答

2

的一種方法是設置flex-grow: 1; flex-basis: 0所以3列均勻分佈,那麼你就可以居中文本或在中間的一個內容。

我使用text-align來居中列。您也可以使用display: flex; justify-content: center;來做同樣的事情。

.flex { 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: space-between; 
 
} 
 
.flex > span { 
 
    flex: 1 0 0; 
 
} 
 
.flex > span:nth-child(2) { 
 
    text-align: center; 
 
}
<div class="flex"> 
 
    <span style="font-size:12px;">small</span> 
 
    <span style="font-size:20px;">Client Index</span> 
 
    <span style="font-size:18px;">Lots of content that moves the center</span> 
 
</div>

1

使用嵌套的Flex容器和auto利潤。

.flex-container { 
 
    display: flex; 
 
} 
 

 
.flex-item { 
 
    flex: 1; 
 
    display: flex; 
 
    justify-content: center; 
 
} 
 

 
.flex-item:first-child>span { 
 
    margin-right: auto; 
 
} 
 

 
.flex-item:last-child>span { 
 
    margin-left: auto; 
 
} 
 

 
/* non-essential */ 
 
.flex-item { 
 
    align-items: center; 
 
    border: 1px solid #ccc; 
 
    background-color: lightgreen; 
 
    height: 40px; 
 
}
<div class="flex-container"> 
 
    <div class="flex-item"><span>short</span></div> 
 
    <div class="flex-item"><span>medium</span></div> 
 
    <div class="flex-item"><span>lonnnnnnnnnnnnnnnnnnnng</span></div> 
 
</div>

下面是它如何工作的:

  • 頂層的div是柔性的容器。
  • 每個小孩div現在是一個彈性項目。
  • 每個項目被給予flex: 1以平均分配容器空間。
  • 現在這些項目正在消耗該行中的所有空間並且寬度相等。
  • 使每個項目成爲一個(嵌套)柔性容器並添加justify-content: center
  • 現在每個span元素都是居中的flex項目。
  • 使用flex auto頁邊距左移和右移外部span

您也可以放棄justify-content並僅使用auto保證金。

justify-content可以在這裏工作,因爲auto邊距總是優先。從規格:

8.1. Aligning with auto margins

此前對準通過justify-contentalign-self,任何 積極的自由空間被分配到汽車的利潤在這方面。