Govind Rai Govind Rai - 3 months ago 16
CSS Question

Why is the button not centered?

I thought adding a

on an element with a known
will center an element because margins on both sides will become equal. However, I'm not sure where I'm going wrong: how can I center this button on the page?

p {
font-family: helvetica, sans-serif;
font-size: 18px;

button {
background-color: lightblue;
color: white;
padding: 15px 32px;
border-radius: 4px;
border: 5px solid lightblue;


.upload-button {
width: 300px;
margin: 10px auto;


button:hover {
background: white;
border: 5px solid lightblue;
color: lightblue;

html, body {
height: 100%;

body {
width: 960px;
margin: auto;

<button id="upload-button" class="upload-button" type="button">why is this button not centered</button>


A button is an inline element by default, so you can center it by adding a container div around the button and give that container a text-align: center property to align the button correctly.

#container {
   text-align: center;
<div id="container">
    <button>Centered button!</button>

The margin: 0 auto only works when your element is a block-level element. So you could also add display: block to your button to achieve the same thing. Although this would give the button a full-width (100%) by default, so you would need to give it a fixed with too.

#button1 {
  display: block;
  width: 150px;
  margin: 0 auto;
<button id="button1">Centered button!</button>