How to center a button inside a div using CSS?

We often come across situations where we have to center a button inside its parent element. To do that we generally use margin: auto; but that seems not to work.

The reason it doesn’t work is that a <button> is an inline-block level element. So applying margin: auto; has no effect on it. So long story short, we have to first make the <button> a block-level element and then we can apply margin: auto; on it.

There are other methods also that we can use. So, let’s discuss a few easy methods –


Center a button inside a div using margin: auto

As we have already discussed, to center a button inside a div we have to first make it a block-level element. To do that apply display: block; property on the button. Now to center it, you can apply margin: auto;

Example:

div{
   border: 2px solid red;
   padding: 20px;
}
button{
   display: block;
   margin: auto;
}

Center a button inside a div using text-align Property

CSS text-align property can also center a button inside the div element. To do this you have to apply text-align: center; on the div element. But the problem with this method is that all the child elements of this div will be center aligned even if you don’t want them.

Example:

div{
   border: 2px solid red;
   text-align: center;
   padding: 20px;
}

Center a button inside a div using CSS flexbox

The above two methods are good if you want to center align the button only horizontally. But, if you wish to center the button both horizontally and vertically, CSS flexbox is the best choice.

To center a button inside a div element use:

  • justify-content: center; – To center horizontally
  • align-items: center; – To center vertically

Example:

div{
    display: flex;
    justify-content: center;
    align-items: center;
    border: 2px solid red;
    height: 250px;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts