如何定位文本和Div在彼此的顶部,并在中心对齐

How to position text and Div on top of eachother and align them in center?

本文关键字:顶部 对齐 在中心 Div 何定位 定位 文本      更新时间:2023-09-26

所以我不明白。我试图得到一个红色的垂直框显示在页面的中间。我将div的边距设置为auto。然后还有另一个div存放居中文本。在两者上设置自动边距。

但是我希望它对所有高度都有响应。现在它只响应x轴而不是高度

HTML,CSS:

.parentDiv {
  position: relative;
  width: 250px;
  height: 450px;
  margin: auto;
}
#RedBox {
  width: 250px;
  height: 450px;
  background-color: #FF0000;
  margin: auto;
}
#CSText {
  position: absolute;
  top: 45%;
  width: 250px;
  color: black;
  text-align: center;
}
<div class="parentDiv" style="margin-top: auto;">
  <div id="CSText" class="TextAlignCenter">
  </div>
  <div id="RedBox">
  </div>
</div>

flexbox将是一个很好的解决方案:

.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.red-box {
  background-color: red;
  padding: 100px;
  color: white;
}
<div class="container">
  <div class="red-box">text</div>
</div>

我这么做是为了你。https://jsfiddle.net/95ssv6q1/

<div class="parentDiv">
   <div class="inner">
     <div id="RedBox">
     </div>
   </div>
</div>
CSS

.parentDiv {
     display:table;
     width: 100%;
     height: 100%;
     position: absolute;
 }
 .inner{
     display: table-cell;
     vertical-align:middle;
 }
 #RedBox {
    width: 250px;
    height: 450px;
    background-color: #FF0000;
    margin: auto;
}