How to Center Button In CSS & HTML[Horizontally and Vertically]

First you need to create a simple button in HTML and CSS.

HTML

<div class="container">
  <button class="button-1">
    Centered Button
  </button>
</div>

CSS

.button-1 {
  background-color: #a61e4d;
  color: #eee;
  padding: 15px 25px;
  border: none;
}

Center Button Horizontally

Center button using Text Align

The first method to center a button horizontally is using the text-align property in CSS. Add text align property to the container holding the button.

.container {
  text-align: center;
}

Center Button Using Margin

Before Flexbox, using the margin property, was probably the best way to center things on the web. You can still use it by adding the following CSS code to the button.

.button-1 {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

You can also use the shorthand of margin property on the button, which is:

.button-1 {
  display: block;
  margin: 0 auto;
}

Center Button Using Flexbox

Flexbox provides an easy and hack-free way to center a button. Just add the following CSS code to the container holding the button.

.container {
  display: flex;
  justify-content: center;
}

Center Button Vertically

Centering vertically in Flexbox is also a straight forward process.

Start by adding a height to your container.

.container {
  height: 200px;
}

Then use align-items property to center the button vertically.

.container {
  display: flex;
  align-items: center;
}

Center button Horizontally and Vertically

To center a button both horizontally and vertically, combine one of the horizontal methods with the vertical method.

You can use Flexbox only.

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

You can combine margin auto and Flexbox

.container {
  display: flex;
  align-items: center;
  height: 200px;
}

.button-1 {
  display: block;
  margin: 0 auto;
}
author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.