0

I am trying to horizontally center align a button at the bottom of the div. I read some posts and they all suggest using text-align:center; on the parent div, but that isn't working for me.

CSS:

  .col-lg-3{
    text-align: center;
  }
  .btn-primary{
    position: absolute;
    bottom: 0;

HTML:

          <div class="col-lg-3">
            <h1 class="display-6">Lorem Ipsum</h1>
            <p class="text">123456789</p>
            <button onclick="window.location.href='projects/test.html'" type="button" class="btn btn-primary" style="margin:0 auto;display:block;">Learn More</button>
          </div>

When I run this code the button is at the bottom of the div, but isn't center aligned. Could anyone help me out with this?

Thank You

  • Just remove `position: absolute;` The button will be centered by the `text-align: center` of its parent. Unless there is other CSS you have not included in your question. – emsoff Apr 28 '20 at 17:19

2 Answers2

0

Because it's position: absolute; for position absolute you have to do like below:

.btn-primary{
position: absolute;
bottom: 0;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}

NOTE: If the height of the parent div is auto and it's changing with the content you don't need position: absolute; just remove position: absolute; and bottom: 0;

Evik Ghazarian
  • 1,685
  • 1
  • 5
  • 20
  • Is there another way to do it, I am trying to keep my css as small as possible. –  Apr 28 '20 at 17:24
  • you can simplify margin to margin: 0 auto 0 auto; which is margin: top right bottom left; but that's all if you want to keep position: absolute; – Evik Ghazarian Apr 28 '20 at 17:28
0

The cleanest solution is to remove position: absolute, which requires setting left and right to center. This is not necessary since the button will be centered with the text-align: center CSS of the parent. This is plenty to horizontally center.

 .col-lg-3{
    text-align: center;
 }

Example.

enter image description here

emsoff
  • 1,493
  • 2
  • 11
  • 16
  • So I removed position:absolute; and now the button is in the center but it isn't at the bottom of the div. How do I fix this? –  Apr 28 '20 at 17:24
  • @ShalajWadhwa it is at the bottom. You can see in the screenshot I just added that this is the case. – emsoff Apr 28 '20 at 17:30