[英]How to vertically center the contents of a flexbox item
我正在嘗試使用justify-content:stretch;
flex;來固定flexbox項目的CONTENTS justify-content:stretch;
似乎使用display:table-cell;vertical-align:middle;
的舊技巧display:table-cell;vertical-align:middle;
在這種情況下不起作用。 什么
.flex-container {
display:flex;
align-items:center;
justify-content:stretch;
}
.flex-item {
align-self:stretch;
}
<div class="flex-container">
<div class="flex-item">I want to be vertically centered! But I'm not.</div>
</div>
在你回答之前:對於我的要求似乎有很多困惑。 我正試圖將flex項目的內容居中。 使用justify-content:stretch
,項目的高度將延伸到容器的整個高度,但項目的內容會浮動到頂部(至少在Chrome中)。
“一張圖片勝過千言萬語。” (A)是我已經得到的。 (B)是我想要的。
可以通過display
每個彈性項目display
為flex
容器,然后通過align-items
屬性垂直align-items
內容來align-items
,如下所示:
.flex-container { display:flex; align-items:center; height: 200px; /* for demo */ } .flex-item { align-self:stretch; display:flex; align-items:center; background-color: gold; /* for demo */ }
<div class="flex-container"> <div class="flex-item"> I want to be vertically centered! <s>But I'm not.</s> </div> </div>
作為旁注,如果省略align-items:center;
聲明.flex-container
你可以安全地刪除align-self:stretch;
來自flex項目。
我不確定我是否正確解釋了您的請求,但我認為您正在嘗試使用“justify-content:stretch;” 什么時候你應該使用flex-grow。
我的樣本我使用flex:1 auto; 這只是設置一些flex屬性的簡寫。
HTML:
<div class="flex-container">
<div class="flex-item">I'm top dog!
</div>
<div class="flex-item flex-center">
I want to be vertically centered! And I am!
</div>
</div>
CSS:
*{
box-sizing:border-box;
padding:5px;
}
.flex-container {
border: 1px solid;
display:flex;
align-items:center;
height: 100px;
}
.flex-item {
flex: 1 auto;
border: 1px solid green;
height:100%;
display:flex;
justify-content:center;
}
.flex-center {
align-items: center;
}
Flex屬性:
https://developer.mozilla.org/en-US/docs/Web/CSS/flex
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.