ag_dhruv ag_dhruv - 7 months ago 11
HTML Question

Button does not get centered

Why is it that a button placed inside a

flex
container is centered by using
margin : 0px auto;
, but a button placed inside a normal container is not?

Also, what can I do to center the button in the normal container (I cannot change my HTML, so a CSS solution would be appreciated.)

HTML

<div class="flex-container">
<button>Button in flex</button>
</div>
<div class="normal-container">
<button>Button in normal</button>
</div>


CSS

.flex-container{
display:flex;
background:yellow;
}

.normal-container{
background:green;
}

button{
margin : 0px auto;
}


jsFiddle link : https://jsfiddle.net/r8h3d9wy/1/

Answer

text-align:center on the parent as inputs/buttons are inline level elements.

margin:0 auto in flex-containers works because that's the way alignment works on flex-items. It effectively removes the inline level nature and makes it a flex-child.

.flex-container {
  display: flex;
  background: yellow;
  justify-content: center;
}
.normal-container {
  background: green;
  text-align: center;
}
<div class="flex-container">
  <button>Button in flex</button>
</div>
<div class="normal-container">
  <button>Button in normal</button>
</div>