Juneikerc.com

How to Center a Button with CSS

Featured image of the post: How to Center a Button with CSS

Centering elements on a web page may seem simple, but challenges often arise when trying to achieve the desired effect. In this article, you will learn how to center a button using CSS.

Centering a button using flexbox

Thanks to flexbox, we can create flexible and responsive layouts. To center a button using flexbox, you need to set the property display: flex; on the container element (in this case, a div) and the property justify-content: center; on the child element (in this case, the button).

html
<div>
<button>Button center</button>
</div>
css
div {
display: flex;
justify-content: center;
}
Important

With flexbox, you can also vertically center the button using the align-items: center; property.

Using the margin: 0 auto property

Another way to center a button is by using the margin property. For this, you should turn the button into a block-level element (display: block) and apply the margin: 0 auto; property to it.

html
<div>
<button>center button</button>
</div>
css
div {
background-color: rgba(110, 165, 237, 0.686);
height: 100px;
}
button {
display: block;
padding: 0.5rem 1rem;
width: 200px;
margin: 0 auto;
}

Using the text-align property in the container

The text-align property in CSS, apart from being used to center the text within an element, can also be implemented to horizontally center a button.

html
<div>
<button>Center Button</button>
</div>
css
div {
text-align: center;
}

Knowing how to center buttons in CSS is essential for improving the design of our web pages. Remember that it's important to consider the page's design and use the method that best suits your needs.

Thank you very much for reading, and I hope this post has been helpful, and you managed to center the buttons on your website thanks to CSS.

Juneiker Castillo freelance web developer

I am Juneiker Castillo, a passionate front-end web developer deeply in love with programming and creating fast, scalable, and modern websites—a JavaScript enthusiast and a React.js lover ⚛️.

About me