Home > Web Front-end > CSS Tutorial > How Can I Center a Button Within a Div?

How Can I Center a Button Within a Div?

Patricia Arquette
Release: 2024-12-22 10:35:46
Original
116 people have browsed it

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;
}
Copy after login

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%;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template