css 如果容器的高度未知,如何使div垂直居中?

arknldoa  于 2023-03-05  发布在  其他
关注(0)|答案(2)|浏览(146)

我如何将橙色框居中在剩下的可见绿色区域?如果主框太大(100vh-20px * 2-h的顶部条),它应该只使用最小的距离顶部条和容器的结束-这里定义为边距。

#container {
  min-height: 100vh;
  background-color: green;
  display: flex;
  flex-direction: column;
}

#topBar {
  background-color: yellow;
  top: 0;
}

#mainBox {
  background-color: orange;
  margin: 20px 0;
}




body {
margin: 0;
}
<div id="container">
  <div id="topBar">Height of this is unknown!<br>.</div>
  <div id="mainBox">Height of this is also unknown. It should be vertically in the center of the REMAINING VISIBLE green area<br>.</div>
</div>
xqk2d5yq

xqk2d5yq1#

你可以用flexbox来居中。类似的东西应该很好

#container {
  min-height: 100vh;
  background-color: green;
  display: flex;
  flex-direction: column;
}

#topBar {
  background-color: yellow;
  top: 0;
}

#mainBox {
  background-color: orange;
  margin: 20px 0;
}

body {
margin: 0;
}

.center {
  display: flex;
  flex: 1;
  align-items: center;
}
<div id="container">
  <div id="topBar">Height of this is unknown!<br>.</div>
  <div class="center">
  <div id="mainBox">Height of this is also unknown. It should be vertically in the center of the REMAINING VISIBLE green area<br>.</div>
  </div>
</div>
watbbzwu

watbbzwu2#

您可以将绿色容器的高度设置为auto,这意味着它的高度将基于其内容长度。

#container {
  min-height: 100vh;
  background-color: green;
  display: flex;
  flex-direction: column;
}

#topBar {
  background-color: yellow;
  top: 0;
}

#mainBox {
  background-color: orange;
  margin: auto 0; /*Here is changed*/
}

body {
margin: 0;
}
<div id="container">
  <div id="topBar">Height of this is unknown!<br>.</div>
  <div id="mainBox">Height of this is also unknown. It should be vertically in the center of the REMAINING VISIBLE green area<br>.</div>
</div>

相关问题