【问题标题】:How do you center an element w.r.t an already centered element in flex?你如何在 flex 中居中一个元素 w.r.t 一个已经居中的元素?
【发布时间】:2022-01-07 20:51:21
【问题描述】:

[![红色:在画布上居中:黑色:在画布中心和顶部之间居中][1]][1]

使用flex,很容易将元素定位在 div 的中心。但是如何相对于已经居中的元素使用 flex 来完成呢?

下面显示的代码是我迄今为止提出的最好的。我可以将红色方块居中居中,但无法让其上方的蓝色方块在红色方块和顶部边框之间垂直居中对齐。

.flex {
  border-style: solid;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: white;
  height: 100vh
}

.square {
  height: 10px;
  width: 10px;
}

#square1 {
  background-color: blue;
}

#square2 {
  background-color: red;
}

.flexdivider {
  display: flex;
  flex-direction: column
  justify-content: center;
  align-items: center;
  flex: 1;
}

p {
  color: white;
}
<body>
  <div class="flex">
    <div class="flexdivider">
      <div class="square" id="square1"></div>
    </div>
     <div class="flexdivider">
       <div class="square" id="square2"></div>
    </div>
     <div class="flexdivider">
     </div>
    </div>
  </div>
</body>
[1]:https://i.stack.imgur.com/4lUop.png

【问题讨论】:

  • 请贴出您到目前为止尝试的代码
  • 刚刚发布。我想弄清楚如何将蓝色方块居中在红色方块和环绕 div 边框之间。

标签: html css flexbox


【解决方案1】:

我创建了 2 个分离的方法。

h2{
  color: #333;
}
.box,.fakebox{
  width: 30px;
  height: 30px;
  background-color: red;
}

/* Example #1 */
.container-box-1{
  background-color: #eee;
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: relative;
}
.fakebox{
  opacity: 0;
}
.box2{
  position: absolute;
  top: 25%;
  left: 50%;
  transform: translate(-50%,-50%)
}
<h2>Example #1 (Using Display Flex and position absolute)</h2>
<div class="container-box-1">
  <div class="box"></div>
  <div class="box box2"></div>
</div>

【讨论】:

  • 感谢您的回答。您能否修改您的答案以显示我的问题中描述的两个框?我了解您只是在屏幕上半部分居中显示一个框。但我希望能够让一个框居中在屏幕的上半部分和一个居中在屏幕的中心。我不确定你的方法是否仍然适用于这种情况?
  • 请检查一下,我已经编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 2014-09-18
  • 1970-01-01
  • 2017-05-13
  • 2021-12-06
  • 2019-01-06
  • 2017-05-15
  • 2012-09-25
  • 1970-01-01
相关资源
最近更新 更多