ag_dhruv ag_dhruv - 6 months ago 15
HTML Question

Button does not get centered in block-level container

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.)



.flex-container {
display: flex;
background: yellow;
}
.normal-container {
background: green;
}
button {
margin: 0px auto;
}

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





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>