当 flex-direction 为 column 时,如何将 div 对齐到顶部?
How do I align a div to the top when flex-direction is column?
我在容器中有两个 div 标签。我想使用 flex box 并将第一个 div 标签对齐到顶部,另一个相对于容器居中。我该怎么做?
使用align-items: flex-start
仅当 flex-direction 为 column 时将其向左移动。 css 将其移动到顶部的等价物是什么?
代码笔:https://codepen.io/GMSg68/pen/aGpOpG
.box {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 500px;
border: 1px solid blue;
}
.box div {
width: 100px;
height: 100px;
border: 1px solid darkgray;
}
.box div:nth-child(1) {
/* How do I push the first div tag to the top? */
background-color: lightgray;
}
.box div:nth-child(2) {
background-color: lightblue;
}
<div class="box">
<div>One</div>
<div>Two</div>
</div>
为第 n 个子节点 (2) 添加 margin top 和 bottom auto div。然后添加 -50% 的 Y 变换以将其对齐到中心。这假设两个 div 高度相同。
.box div:nth-child(2){
background-color: lightblue;
margin-top: auto;
margin-bottom: auto;
transform: translateY(-50%);
}
我在容器中有两个 div 标签。我想使用 flex box 并将第一个 div 标签对齐到顶部,另一个相对于容器居中。我该怎么做?
使用align-items: flex-start
仅当 flex-direction 为 column 时将其向左移动。 css 将其移动到顶部的等价物是什么?
代码笔:https://codepen.io/GMSg68/pen/aGpOpG
.box {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 500px;
border: 1px solid blue;
}
.box div {
width: 100px;
height: 100px;
border: 1px solid darkgray;
}
.box div:nth-child(1) {
/* How do I push the first div tag to the top? */
background-color: lightgray;
}
.box div:nth-child(2) {
background-color: lightblue;
}
<div class="box">
<div>One</div>
<div>Two</div>
</div>
为第 n 个子节点 (2) 添加 margin top 和 bottom auto div。然后添加 -50% 的 Y 变换以将其对齐到中心。这假设两个 div 高度相同。
.box div:nth-child(2){
background-color: lightblue;
margin-top: auto;
margin-bottom: auto;
transform: translateY(-50%);
}