如何定位文本和Div在彼此的顶部,并在中心对齐
How to position text and Div on top of eachother and align them in center?
所以我不明白。我试图得到一个红色的垂直框显示在页面的中间。我将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/