Making the button center can sometimes be tricky as there are numerous ways to achieve it using CSS. Here are the 3 options that you can use right now to center the button.
How to use
margin: auto to center the button
The first and perhaps the simplest option is adding
margin: 0 auto and then add
display: block to make the button center.
margin: 0 auto;
margin: 0 auto is a short form of setting the top and bottom margins to 0 and the left and right margins to auto. The margin auto is what causes the button to be centered, and a display block is needed as it will work only in block elements.
How to center a button using a
div element tag
The second option is to wrap the button with the
div element tag and then use
text-align: center to center the button. It’s like you’re making a text to be centered.
The downside of this approach is every time you want to center a button, you will have to create a new
div element just for this button. And if you have a lot of buttons that need frequent styling updates, it’ll quickly become a hassle to maintain it. In that case, you are better off using option one.
In short, if you insist on using this approach, do it for few buttons only.
How to center a button using CSS
The third option is to use a flexbox to center a button. This approach is ideal if you are already using flexbox on a web page and the button is inside the parent element.
To center a button with a flexbox, you should do 2 things:
- first, add
display: flexto a button’s parent element so that you’ll activate flexbox features
- then add
justify-content: centerso that the button will be centered
In the example below,
div is the parent element of the button.
And there you have it! These are the 3 ways you can use to center a button in CSS.