How to Center a Button Both Horizontally and Vertically within a Div

If you have faced the problem of centering a button within a <div>, you can find some solutions in our snippet.

We’ll show step by step how to overcome this problem.

Let’s start with creating HTML.

Create HTML

  • Use a <div> with an id “wrapper”.
  • Add a <button> with a type “button”.
<div id="wrapper">
  <button type="button">W3Docs</button>
</div>

Add CSS

  • Set the width, height, and border properties for the wrapper.
  • Specify the height, width, top and left properties for the button.
  • Set the position to “relative” to place the button relative to its normal position.
  • Add the margin to the button.
#wrapper {
  width: 100%;
  height: 400px;
  border: 2px solid #000;
}

button {
  height: 20px;
  position: relative;
  margin: -20px -50px;
  width: 100px;
  top: 50%;
  left: 50%;
}

Let’s see the result of our code.

Example of centering a button inside a <div>:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #wrapper {
        width: 100%;
        height: 400px;
        border: 2px solid #000;
      }
      button {
        height: 20px;
        position: relative;
        margin: -20px -50px;
        width: 100px;
        top: 50%;
        left: 50%;
      }
    </style>
  </head>
  <body>
    <div id="wrapper">
      <button type="button">W3Docs</button>
    </div>
  </body>
</html>

Result

Next, let’s see an example where we use Flexbox to achieve the effect we want.

Example of centering a button inside a <div> using Flexbox:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #wrapper {
        width: 100%;
        height: 300px;
        border: 2px solid #000;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      button {
        height: 30px;
        width: 90px;
      }
    </style>
  </head>
  <body>
    <div id="wrapper">
      <button type="button">W3Docs</button>
    </div>
  </body>
</html>

In the example above, we set the display to “flex”, then specified the values of align-items and justify-content as “center”.