[英]CSS3 flexbox: vertically center two different sized items, but make their top align at the same height
靈感來自:
擺弄問題: http : //jsfiddle.net/Nbknc/22/
我試圖實現的目標:
我想讓第二個按鈕的文本以與第一個按鈕的文本相同的高度開始。
的HTML
<section class="buttonsSection">
<a class="button" href="#">Very Long Word aaaa xx ccc ddd ee</a>
<a class="button" href="#">Short Phrase</a>
</section>
的CSS
.button {
padding: 10px 15px;
width: 150px;
background-color: deepskyblue;
color: white;
margin: 3px;
text-align: top;
display: flex;
flex-direction: column;
justify-content: center;
}
.buttonsSection {
margin: 30px 0;
display: flex;
justify-content: center;
height: 500px;
}
body
{
width: 20%; /*Simulate page being reduced in size (i.e. on mobile)*/
margin: 0 auto;
}
我想要它的外觀照片
編輯我使用flexbox和justify-content的原因是使其與不同的屏幕尺寸一起使用。 Flexbox可以完美分配空間。 添加填充不是最佳選擇,因為即使屏幕的高度為200像素,填充也會保持不變。
這是一種方法,我在其中添加了一個額外的包裝器
.buttonsSection { display: flex; flex-direction:column; justify-content: center; height: 400px; border: 1px solid; width: 200px; margin: 0 auto; } .buttonsWrap { margin: 30px 0; display: flex; } .button { padding: 50px 15px; width: 150px; background-color: deepskyblue; color: white; margin: 3px; text-align: top; }
<section class="buttonsSection"> <div class="buttonsWrap"> <a class="button" href="#">Very Long Word aaaa xx ccc ddd ee</a> <a class="button" href="#">Short Phrase</a> </div> </section>
您可以通過從按鈕中刪除flexbox屬性並使用以下CSS在按鈕文本周圍添加span
來實現此目的:
position: relative;
top: 50%;
transform: translateY(-50%);
您可能需要使用這些百分比才能使事情理想地排成一列,但這會讓您陷入困境。
編輯: http : //jsfiddle.net/Dneilsen22/36yL3y5m/5/
刪除.button的justify-content並增加頂部填充將實現此目的。
.button {
padding: 100px 15px;
width: 150px;
background-color: deepskyblue;
color: white;
margin: 3px;
text-align: top;
display: flex;
flex-direction: column;
}
我更新了小提琴“建議”(如果您不需要)。
.button {
padding: 50% 15px 0 15px;
width: 150px;
background-color: deepskyblue;
color: white;
margin: 3px;
}
.buttonsSection {
margin: 30px 0;
display: flex;
flex-direction:row;
height: 500px;
}
現在它更簡單了,現在您可以在按鈕上添加所需的填充,以使兩個按鈕中的文本都與相等的頂部填充對齊。
更新
包括對您的html和CSS的一些更改
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.