Home >Web Front-end >CSS Tutorial >How Can I Center a Button Within a Div?
Creating Centered Buttons within a div
Centering a button within a div can be achieved through various methods. For a div with a 100% width, here's how you can accomplish it:
Using Flexbox (Updated Answer)
Flexbox provides a modern and flexible approach:
#wrapper { display: flex; align-items: center; justify-content: center; }
This aligns the button to the center both vertically and horizontally.
Using Fixed Width and Positioning (Original Answer)
If the button has a fixed width and height, you can use relative positioning and negative margins:
button { height: 20px; width: 100px; margin: -20px -50px; position: relative; top: 50%; left: 50%; }
Alternatively, for horizontal alignment only, use margin: 0 auto; or set text-align: center; on the div.
The above is the detailed content of How Can I Center a Button Within a Div?. For more information, please follow other related articles on the PHP Chinese website!