flex-box-self align

Easy ways to center buttons in a div

Making buttons appear in the center of a div could sometime be a challenge, however it can also be as simple as creating the buttons if you know the code to actually apply to either the button or the div where the buttons are sitting

1. Using flex box

One method to actually center your buttons in a div is to use flex box property in your CSS, the code below has a div with a class of container which contains four buttons.

HTML

 <div class=”container”>

 <button>button1</button>

<button>button2</button>

<button>button3</button>

<button>button4</button>

 </div>

CSS

.container {

width: 400px;

height: 400px;

background-color: aqua;

display: flex;

justify-content: center;

align-items: center;

 }

 

The code above will actually center your buttons in a div. however, if you have other contents in your div like text, image, links, etc before the buttons, you could wrap the buttons in separate div and use the same styling on the button div as shown below

HTML

<div class=”parent”>

       <h1>text</h1>

       <img src=”” alt=””>

        <a href=””></a>

   <div class=”button-container”>

      <button>button1</button>

      <button>button2</button>

      <button>button3</button>

     <button>button4</button>

       </div>

</div> 

CSS

.parent {

width: 400px;

height: 600px;

background-color: blue;

}

.button-container {

background-color: aqua;

display: flex;                                                         

justify-content: center;

 align-items: center;

1. Using margin

Just in case you are new to flex and you probably do not know how it works, you can click here to learn how to use flex box property, however, there is also a different way you can actually make your buttons appear at the center. This time, we will be using just margin, and just to show how it works, let us make the following changes to our css,

HTML

 <div class=”btn-parent”>

      <div class=”button-container”>

        <button>button1</button>

        <button>button2</button>

        <button>button3</button>

        <button>button4</button>

      </div>

    </div>

And next we add the following styling

CSS

.btn-parent {

  width: 400px;

  height: 50px; 

  background-color: aqua;

}

.button-container {

  margin: 0 auto;

  width: fit-content;

}

button{

margin-top:15px;

}

The reason we have to do it in two ways is that, I would not want you to see some code online and be wondering how it was done, and hopefully, you understand how you can place your buttons in the center using just margin property and flex box. Again, you can follow this link to learn how to use flex box

Leave a Comment

Your email address will not be published. Required fields are marked *