【问题标题】:How do I align a div to the top when flex-direction is column? [duplicate]当 flex-direction 为列时,如何将 div 对齐到顶部? [复制]
【发布时间】:2018-10-09 04:41:42
【问题描述】:

我在一个容器中有两个 div 标签。我想使用弹性框并将第一个 div 标签与顶部对齐,另一个相对于容器居中。我该怎么做?

使用align-items: flex-start 仅在 flex-direction 为列时将其向左移动。将其移至顶部的等效 css 是什么?

codepen: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>

【问题讨论】:

  • 另一个居中。水平和垂直居中还是仅水平居中?
  • 另一个水平和垂直居中。

标签: html css flexbox centering


【解决方案1】:

将边距顶部和底部自动添加到 nth-child(2) div。然后添加 -50% 的 Y 变换以使其与中心对齐。这假设两个 div 的高度相同。

.box div:nth-child(2){
  background-color: lightblue;
  margin-top: auto;
  margin-bottom: auto;
  transform: translateY(-50%);
}

【讨论】:

  • 谢谢,这似乎有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 2013-12-06
  • 2016-11-19
  • 2015-09-15
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多