Home >Web Front-end >CSS Tutorial >How to Center a Button Horizontally (and Vertically) Within a Full-Width Div?

How to Center a Button Horizontally (and Vertically) Within a Full-Width Div?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 17:53:09838browse

How to Center a Button Horizontally (and Vertically) Within a Full-Width Div?

Centering a Button within a Div with 100% Width

A common need in CSS is centering a button within a div that spans the entire width of the page. To achieve this, there are several methods available.

One approach is to use Flexbox. By setting the display property of the div to flex and adding justify-content: center and align-items: center, the div becomes a flexbox container that centers its children vertically and horizontally.

#wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}
button {
  /* Other styles */
}

If vertical alignment is not necessary, you can simply use justify-content: center.

#wrapper {
  display: flex;
  justify-content: center;
}
button {
  /* Other styles */
}

For a more traditional approach, you can set the margin property of the button to auto. This will center the button horizontally within the div.

button {
  margin: 0 auto;
  /* Other styles */
}

Alternatively, you can set the text-align property of the div to center. This will center all the elements within the div, including the button.

div {
  text-align: center;
}
button {
  /* Other styles */
}

These are just a few methods for centering a button within a div. The best approach will depend on the specific requirements of your layout.

The above is the detailed content of How to Center a Button Horizontally (and Vertically) Within a Full-Width 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