如何用css使文本在页面底部居中?

问题描述 投票:0回答:4

我试图在 html 页面的 bottom-center 放置一些文本,但它没有对齐。

main {
    position: relative;
    text-align: center;
    max-width: 240px;
    margin: 0 auto;
}

.bottom {
    position:fixed;
    bottom:0;
}
<main>
    <div>
        <h1>Hello</h1>
    </div>
    <div class=bottom>
        <span>Bottom text</span>
    </div>
</main>

我尝试了各种选项,包括 position:absolute; (文本不在底部)和 margin: 0 auto; 在底部 css (没有效果)

我错过了什么?

html css css-position
4个回答
0
投票

尝试这样的事情:

main {
    position: relative;
    text-align: center;
    max-width: 240px;
    margin: 0 auto;
    height: 100vh;
}

.bottom {
    position: absolute;
    bottom: 0;
    left: 50%; 
    transform: translateX(-50%);
 
}

<main>
    <div>
        <h1>Hello</h1>
    </div>
    <div class=bottom>
        <span>Bottom text</span>
    </div>
</main>

0
投票

left: 50%;
transform: translateX(-50%);
添加到
bottom
以使其居中。
left: 50%;
将元素的左边缘移动到其容器的中间,而
transform: translateX(-50%);
将其向左移回其自身宽度的 50% – 这两个组合将其水平居中。

main {
    position: relative;
    text-align: center;
    max-width: 240px;
    margin: 0 auto;
}

.bottom {
    position:fixed;
    bottom:0;
    left: 50%;
    transform: translateX(-50%);
}
<main>
    <div>
        <h1>Hello</h1>
    </div>
    <div class=bottom>
        <span>Bottom text</span>
    </div>
</main>


0
投票

确保底部跨越其父容器的整个宽度,占据 100% 的可用水平空间。当将其位置设置为固定在其相对父容器的底部时,请确保从左角开始并水平延伸以覆盖父容器的整个宽度。

main {
  position: relative;
  text-align: center;
  max-width: 240px;
  margin: 0 auto;
}

.bottom {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
}
<main>
  <div>
    <h1>Hello</h1>
  </div>
  <div class=bottom>
     <span>Bottom text</span>
  </div>
</main>


0
投票

使用

display: flex
(使其独立于
text-align: center
上的
main
):

main {
    position: relative;
    text-align: center;
    max-width: 240px;
    margin: 0 auto;
}

.bottom {
    position:fixed;
    bottom:0;
    /* solution with flexbox: */
    display: flex;
    right: 0;
    left: 0;
    justify-content: center;
}
<main>
    <div>
        <h1>Hello</h1>
    </div>
    <div class="bottom">
        <span>Bottom text</span>
    </div>
</main>

© www.soinside.com 2019 - 2024. All rights reserved.