How to center a button using CSS

Posted on Aug 20, 2021

Let's look at how you can center a button horizontally and vertically using CSS

To center an HTML <button> element, you need to add the text-align:center CSS property to the parent container of the button element.

For example, suppose you have a <div> element that contains two button elements, then you need to add the CSS property to the <div> tag:

<div style="text-align:center">
  <button>Click me</button>
  <button>No, click me instead</button>

The output will be as shown below:

Alternatively, you can also set the button in the middle of the <body> element by changing the display level to block and adding margin: 0 auto to the <button> tag.

The following example:

  <button style="display:block; margin: 0 auto;">Click me</button>

Will place the button in the center of the HTML body horizontally.

Centering a button using flexbox and grid CSS model

You can also center a <button> element by changing the container element’s display mode to flex or grid and add the justify-content:center property to it.

For example, suppose you have a <div> as the container of the <button> element, then this CSS rule will put the content of the <div> centered horizontally:

.center-h {
  display: flex; /* or display:grid */
  justify-content: center;

The benefit of using flexbox or grid CSS model is that you can center the content both vertically and horizontally.

While the above CSS will center the content horizontally, the code below will center it vertically:

.center-v {
  display: flex;
  align-items: center;

To see the content centered vertically, let’s add one more class to set the <div> element height to 500:

.h-500 {
  height: 500;

Finally, add all the classes assigned to the CSS rule above to the containing <div> tag as follows:

<div class="h-500 center-v center-h">
  <button>Click me</button>

The output will be as shown below:

And that’s how you can center a button using CSS 😉

Related articles:

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.