52

I don't want to add CSS to my div element (e.g. <div style="text-align: center;">).

I only want to add CSS code to the button element.

<div>
  <button>Button</button>
</div>

How can I center the button horizontally in this case?

Penny Liu
  • 7,720
  • 5
  • 40
  • 66
weilou
  • 3,869
  • 8
  • 37
  • 56
  • Related: https://stackoverflow.com/questions/15300234/how-can-i-make-a-button-element-be-horizontally-displayed-in-center-alignment-in/ – TylerH Jul 11 '18 at 02:47

3 Answers3

124
button {
    margin:0 auto;
    display:block;
}

button {
  margin: 0 auto;
  display: block;
}
<div>
  <button>Button</button>
</div>
j08691
  • 190,436
  • 28
  • 232
  • 252
  • 3
    If you're using this in the real world, you'll need to increase the specificity of that unless you want the button element centered everywhere. – Josh Burgess Mar 08 '13 at 17:55
  • 1
    I've a question. Block element will use full width of its parent element. See http://jsfiddle.net/xmpDD/1. Why doesn't button element use div element's full width. The truth we get is that the width of button element is 54 pixel. I can't understand this. Thank you! – weilou Mar 08 '13 at 18:01
  • Is the `0` actually necessary? `margin: auto;` seems to work in FF, IE, and Chrome. – Adi Inbar May 06 '15 at 00:52
  • @AdiInbar - the 0 is just the top and bottom margins. Assumption here is horizontal center only. You can set it to auto and then it will vertically center based on the container height. – tjmoore Nov 17 '15 at 19:07
5

Others have already mentioned the margin: 0 auto; method, but if you wanted an explanation, the browser splits up the available space in whatever container your element is in.

Also important to point out is you'll probably need to give your element a width, too, for this to work correctly.

So, overall:

button {
    display:inline-block; //Typically a button wouldn't need its own line        
    margin:0 auto;
    width: 200px; //or whatever
}
Phillip Schmidt
  • 8,525
  • 3
  • 40
  • 65
4

You need display: block; margin: auto; on the <button>. jsFiddle

dezman
  • 15,356
  • 8
  • 48
  • 82
  • I've a question. Block element will use full width of its parent element. See http://jsfiddle.net/xmpDD/1. Why doesn't button element use div element's full width. The truth we get is that the width of button element is 54 pixel. I can't understand this. Thank you! – weilou Mar 08 '13 at 18:01
  • 1
    @weilou Actually, block level elements don't necessarily get the width of their parent. Their combined width, margins, and padding equals the width of their parent. Hope it helped! – Phillip Schmidt Mar 08 '13 at 18:06
  • Thank you very much! Phillip. Your comment helps me! – weilou Mar 08 '13 at 18:12
  • I'm not sure why this was downvoted. It's essentially the same as the accepted answer, except it omits a `0` that as far as I can tell isn't needed, and it was posted effectively at the same time. – Adi Inbar May 06 '15 at 01:00