How to center text at the bottom of the page with css?

55 views Asked by At

I am trying to place some text at the bottom-center of an html page but it is not aligned.

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>

I have tried various options including position:absolute; (text not at bottom) and margin: 0 auto; in bottom css (no effect)

What am I missing?

4

There are 4 answers

0
Wong0790 On BEST ANSWER

Ensure that the bottom spans the full width of its parent container, occupying 100% of the available horizontal space. When setting its position to fixed at the bottom of its relative parent, make sure the starts from the left corner and extends horizontally to cover the entire width of the parent container.

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
Johannes On

Add left: 50%; and transform: translateX(-50%); to bottom to center it. left: 50%; moves the left edge of the element to the middle of its container and transform: translateX(-50%); moves it back to the left by 50% of its own width – those two in combination center it horizontally.

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
Adarru78 On

Try something like this:

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
connexo On

Using display: flex (makes it independent from text-align: center on 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>