How to center a button within a div with CSS?

Spread the love

Sometimes, we want to center a button within a div with CSS.

In this article, we’ll look at how to center a button within a div with CSS.

How to center a button within a div with CSS?

To center a button within a div with CSS, we use flexbox.

For instance, we write

<div style="width: 100%; height: 100%; border: 1px solid" id="wrapper">
  <button type="button">hello</button>
</div>

to add a div with a button.

Then we write

#wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

to select the div and make it a flex container with display: flex;.

Then we center its contents vertically with align-items: center;.

And we center its contents horizontally with justify-content: center;.

Conclusion

To center a button within a div with CSS, we use flexbox.

Leave a Reply

Your email address will not be published.