垂直对齐两个弹性项目 [英] Vertically aligning two flex items
问题描述
我有一个弹性容器 .container
和两个弹性项目: item-one
和项二
。我想垂直居中第一项并将第二项固定在底部。
我不知道如何垂直对齐此上下文中的第一项。
HTML:
< div class =container>
< div class =item-one>第一项< / div>
< div class =item-two>第二项< / div>
< / div>
CSS:
html,body {
height:100%;
保证金:0;
}
.container {
width:500px;
margin:0 auto;
border:5px纯橙色;
身高:100%;
/ * Flex属性* /
display:flex;
flex-wrap:wrap;
align-items:center;
justify-content:center;
}
.item-one {
border:5px纯黄色;
flex-basis:500px;
}
.item-two {
border:5px纯红色;
align-self:flex-end;
}
CodePen 您可以使用< a href =http://www.w3.org/TR/css-flexbox-1/#auto-margins =nofollow> auto
边距来对齐这样的元素。这将允许您向 auto
保证金的方向分配任何可用空间。
在这种情况下,您可以将 flex-direction
更改为 column
,以便使flexbox项目垂直流动。然后,您可以在第一个Flexbox项目上设置 margin-top:auto
/ margin-bottom:auto
它垂直并确保它上面和下面的空间是相等的。在这样做的情况下,这会将第二项推到底部:
html,body {height:100%; margin:0;}。container {width:500px;保证金:0汽车;边框:5px纯橙色;身高:100%;显示:flex; flex-direction:column} .item-one {border:5px solid yellow; margin:auto 0;}。item-two {border:5px solid red; margin:0 auto;}
< div class =容器> < div class =item-one>第一项< / div> < div class =item-two>第二项< / div>< / div>
b $ b
I have a flex container .container
and two flex items: item-one
and item-two
. I want to vertically center the first item and to stick the second to the bottom.
I don't know how to vertically align the first item in this context.
HTML:
<div class="container">
<div class="item-one">Item One</div>
<div class="item-two">Item Two</div>
</div>
CSS:
html, body {
height: 100%;
margin: 0;
}
.container {
width: 500px;
margin: 0 auto;
border: 5px solid orange;
height: 100%;
/* Flex properties */
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
.item-one {
border: 5px solid yellow;
flex-basis: 500px;
}
.item-two {
border: 5px solid red;
align-self: flex-end;
}
You could use auto
margins to align the elements like that. This will allow you to distribute any positive free space in the direction of the auto
margin.
In this case, you would change flex-direction
to column
in order to make the flexbox items flow vertically. Then you could set margin-top: auto
/margin-bottom: auto
on the first flexbox item in order to center it vertically and ensure that the space above and below it is equal. In doing so, this will push the second item to the bottom:
html, body {
height: 100%;
margin: 0;
}
.container {
width: 500px;
margin: 0 auto;
border: 5px solid orange;
height: 100%;
display: flex;
flex-direction: column
}
.item-one {
border: 5px solid yellow;
margin: auto 0;
}
.item-two {
border: 5px solid red;
margin: 0 auto;
}
<div class="container">
<div class="item-one">Item One</div>
<div class="item-two">Item Two</div>
</div>
这篇关于垂直对齐两个弹性项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!