Skip to content
css

How to center a button using CSS in HTML

Jul 19, 2022Abhishek EH2 Min Read
How to center a button using CSS in HTML

In this article, we will see different ways to center a button in HTML both horizontally and vertically using CSS.

Using text-align method

You can use the css text-align property with a value center to center a button. Applying the style directly to the button will not work. You'll have to create a wrapper element around the button and apply the style to it.

1<div class="button-wrapper">
2 <button>Click Me</button>
3</div>

In the css, provide the following style:

1.button-wrapper {
2 text-align: center;
3}

Using the margin auto method

You can set the margin-left and margin-right to auto so that the button is centered. You also need to set the display property to block since the button, by default, has a display property set to inline-block. When you set the display to block, it will consume the entire width of the screen, and the margin auto will align it to the center.

1<button class="button">Click Me</button>

Update the css to the following:

1.button {
2 display: block;
3 margin: 0 auto;
4}

margin:0 auto will add 0 margin to the top and bottom of the button. If you need only the left and right margin, you can specify margin-left:auto and margin-right:auto.

Using flexbox method

This is my favorite way of centering elements in HTML. Like the first method, you need to add a wrapper div and give it a style display:flex and justify-content:center.

1<div class="button-wrapper">
2 <button class="button">Click Me</button>
3</div>

In the css file, add the following styles:

1.button-wrapper {
2 display: flex;
3 justify-content: center;
4}

Centering the button both vertically and horizontally

You can use the flexbox method to center the button vertically as well.

1<div class="button-wrapper">
2 <button class="button">Click Me</button>
3</div>

In the CSS:

1.button-wrapper {
2 display: flex;
3 justify-content: center;
4 align-items: center;
5 height: 100vh;
6}

Here we have set the height to 100vh, which means it will occupy 100% of the visible screen height. Then we aligned the button to the center.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com