How to Center a Button using CSS Flexbox?

CSS Flexbox is always the best choice when you want to center a button either horizontally or vertically.

To center a button using CSS flexbox, the first thing you need to do is place the button inside a div element and make this div a flex container by applying display: flex; on it.

Now, if you want to center the button horizontally, you have to set the justify-content property to center. And if you want to center the button vertically, you have to set the align-items property to center.

See this example:

Example:

div{
   display: flex;
   justify-content: center;  /* Align Horizontally */
   align-items: center;      /* Align Vertically */
   border: 2px solid orange;
   height: 200px;
}

With this method, you can center any number of buttons inside the container. And even you can set a gap between them. To set the gap between the buttons we have to use the column-gap property.

In the following example, we have centered the two buttons inside the container and set a gap of 20px between them:

Example:

div{
   display: flex;
   justify-content: center;  
   align-items: center;      
   column-gap: 10px;  /* Set a gap of 10px */
   border: 2px solid orange;
   height: 200px;
}

If you want to center the button only horizontally, you have to set the justify-content to center. But this will alone not solve the problem.

This is because by default the flex items stretch to the full height of the flex container. To avoid this problem you have to explicitly set the align-items to flex-start.

See this example:

Example:

div{
   display: flex;
   justify-content: center;
   align-items: flex-start;
   border: 2px solid orange;
   padding: 20px;
}