0

This may be basic but i read in a book that to center something inside a div you should :

  margin-left: auto;
  margin-right: auto;
  width:70%;

so you give it a width and set auto margin. With button it will not work and I also need to add this to make it work :

  display: block;

Why in this case we need it block ?

Curnelious
  • 1
  • 16
  • 76
  • 150

2 Answers2

4

inline/inline-block elements can't have auto value for margin.

If you want to center button without making it a block, you can use text-align: center on it's parent.

Also, button don't have to be a block if it's being centered by a flex/grid parent.

I added a few examples below.

.wrapper-center {
  padding: 20px;
  border: 1px solid blue;
  text-align: center;
}

/* ----- */

.wrapper {
  padding: 20px; 
  margin-top: 20px;
  border: 1px solid red;
}

.centered-button {
  display: block;
  margin: 0 auto;
}

/* ----- */

.flex-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  padding: 20px; 
  border: 1px solid green;
}
<div class="wrapper-center">
  <button>Test</button>
</div>

<div class="wrapper">
  <button class="centered-button">Test</button>
</div>

<div class="flex-wrapper">
  <button>Test</button>
</div>
flppv
  • 4,111
  • 5
  • 35
  • 54
  • `inline elements can't have margin.` --> this is false: https://jsfiddle.net/tj3dmnhf/. And a button is an inline-block element – Temani Afif Mar 17 '19 at 08:12
  • @TemaniAfif you're partly correct, `inline` elements can have side margins(they can't have `margin-top` and `margin-bottom` tho. And `inline-block` can have all margins, except for `auto`. I updated my answer. – flppv Mar 17 '19 at 10:56
0
Display: block

This gives the section or div a whole part of the page to itself, starting from what is essentially a new line and taking up the width of the page. Margin and width statement only affect it because of this. Inline or otherwise don’t have this property requirement due to the fact that their properties become relative to other elements on the same line

EngineersBox
  • 93
  • 1
  • 5