垂直对齐两个弹性项目
Vertically aligning two flex items
我有一个弹性容器 .container
和两个弹性项目:item-one
和 item-two
。我想将第一项垂直居中并将第二项粘贴到底部。
我不知道如何在这种情况下垂直对齐第一项。
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;
}
您可以使用 auto
margins 来对齐元素。这将允许您在 auto
保证金的方向上分配任何正免费 space。
在这种情况下,您可以将 flex-direction
更改为 column
以使 flexbox 项目垂直流动。然后你可以在第一个 flexbox 项目上设置 margin-top: auto
/margin-bottom: auto
以使其垂直居中并确保其上方和下方的 space 相等。在这样做时,这会将第二个项目推到底部:
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>
我有一个弹性容器 .container
和两个弹性项目:item-one
和 item-two
。我想将第一项垂直居中并将第二项粘贴到底部。
我不知道如何在这种情况下垂直对齐第一项。
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;
}
您可以使用 auto
margins 来对齐元素。这将允许您在 auto
保证金的方向上分配任何正免费 space。
在这种情况下,您可以将 flex-direction
更改为 column
以使 flexbox 项目垂直流动。然后你可以在第一个 flexbox 项目上设置 margin-top: auto
/margin-bottom: auto
以使其垂直居中并确保其上方和下方的 space 相等。在这样做时,这会将第二个项目推到底部:
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>