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
Patricia ArquetteOriginal
2024-12-22 10:35:46113browse

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!

Statement:
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