"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to center aligned buttons in a Div?

How to center aligned buttons in a Div?

Posted on 2025-04-19
Browse:583

How Can I Center a Button Inside a Div?

Centering a Button Within a Div

In web development, it's often desirable to center a button within a containing div. Let's explore two solutions to this challenge:

Using Flexbox

Flexbox provides an elegant solution for aligning elements along both axes. To center a button horizontally and vertically within a div:

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

If only horizontal centering is desired, the justify-content property can be used:

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

Margin-Based Approach

Without flexbox, a button can be centered using margins:

button {
  margin: -20px -50px; /* Offset to center */
  position: relative;
  top: 50%;
  left: 50%;
}

For horizontal centering only, one of these two approaches can be used:

  • margin: 0 auto; on the button
  • text-align: center; on the containing div
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3