如何将文本水平居中对齐并对齐到页面底部?

  • 本文关键字:对齐 底部 文本 水平居中 css
  • 更新时间 :
  • 英文 :


我想将文本水平对齐到页面的中心,也可以在页面底部对齐,并带有文本的背景。此处的文本是可变的。我想将文本分成更多行,如果它跨越屏幕尺寸的 30% 以上width

我要么能够将div 对齐到中心,要么粘在页面底部,但不能两者兼而有之。当我给absolutefixedposition时,中心对齐缺失,我必须给left: 30%才能向右移动。

这是 HTML

<div class="div-1">
<div class="div-2">
Hey this is an amazing way to do this
</div>
</div>

这是 CSS:

.div-1 {
height: 100vh;
}
.div-2 {
bottom: 10px;
background-color: black;
position: absolute;
color: white;
font-size: 20px;
max-width: 30%;
}

有人可以建议完美的方法来做到这一点吗?谢谢。

对于初学者,将className更改为class。然后添加

position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;

.div-2

.div-1 {
height: 100vh;
}
.div-2 {
background-color: black;
color: white;
font-size: 20px;
max-width: 30%;
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div class="div-1">
<div class="div-2">
Hey this is an amazing way to do this
</div>
</div>

您应该使用尽可能少的标签。 要使水平居中,请使用文本对齐:居中并确保容器的宽度为 100%。 减小文本的宽度;对容器使用填充。

<footer>
Hey this is an amazing way to do this
</footer>
footer {
position: fixed; bottom: 0; left: 0;
text-align: center; width: 100%; box-sizing: border-box;
padding: 15px 35%; background: blue; color: white;
text-transform: uppercase; font-weight: bold;
}

应该是这样的。你可以像在 React 中使用 className 一样使用它。

.div-1 {
height: 100vh;
}
.div-2 {
bottom: 0;
background-color: red;
position: absolute;
color: white;
font-size: 20px;
max-width: 30%;
height: 400px;
width: 300px;
margin: 0 auto;
text-align: center;
vertical-align: middle;
line-height: 400px;
}
<div class="div-1">
<div class="div-2">
Hey this is an amazing way to do this
</div>
</div>

最新更新