-2

Why does the margin: auto not center the button inside an li in this example? I can however use text-align: center to center it. Why does this happen? I even tried to insert the button inside a container but this still seems to not work.

ul {
  list-style: none;
}

textarea {
  vertical-align: middle;
}

.button {
  background: blue;
  border: solid thin;
  display: block;
  padding: auto;
}

button {
  margin: 0 auto;
  width: 100px;
}
<form action="">
  <ul>
    <li>
      <label for="msg">Message:</label>
      <textarea name="user_message" id="msg" cols="30" rows="10"></textarea>
    </li>
    <li class="button">
      <button type="button">Button</button>
    </li>
  </ul>
</form>
khan
  • 1,466
  • 8
  • 19
Sam
  • 36
  • 4

2 Answers2

0

Add display:inline-blockin button and text-align:center; in li tag:

ul {
  list-style: none;
}

textarea {
  vertical-align: middle;
}

.button {
  background: blue;
  border: solid thin;
  display: block;
  padding: auto;
  text-align:center;/*Css Added*/
}

button {
  margin: 0 auto;
  width: 100px;
  display: inline-block;/*Css Added*/
}
<form action="">
    <ul>
        <li>
            <label for="msg">Message:</label>
            <textarea name="user_message" id="msg" cols="30" rows="10"></textarea>
        </li>
        <li class="button">
            <button type="button">Button</button>
        </li>
    </ul>
</form>
Minal Chauhan
  • 6,025
  • 8
  • 21
  • 41
0

Using margin: auto to center elements only works with elements with a display of block, however buttons have a default display of inline-block which does not let you do that.

The difference between them is:

  • elements with a display of block take up an entire row, you can set the width of them, and you can center them by using margin: 0 auto
  • elements with a display of inline-block don't take up an entire row, but you can still set the width of the element, but they can't be centered by using margin: 0 auto - this is the default style of the button element
  • elements with a display of inline flow inline with everything else, and you cant set the width or height of them

So we can add display: block to the button to sort it out.

ul {
  list-style: none;
}

textarea {
  vertical-align: middle;
}

.button {
  background: blue;
  border: solid thin;
  display: block;
  padding: auto;
}

button {
  margin: 0 auto;
  width: 100px;
  display: block;
}
<form action="">
  <ul>
    <li>
      <label for="msg">Message:</label>
      <textarea name="user_message" id="msg" cols="30" rows="10"></textarea>
    </li>
    <li class="button">
      <button type="button">Button</button>
    </li>
  </ul>
</form>
corn on the cob
  • 2,093
  • 3
  • 18
  • 29