How can I horizontally center a button element in a div element?

纵饮孤独 提交于 2019-12-20 09:27: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?


回答1:


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

button {
  margin: 0 auto;
  display: block;
}
<div>
  <button>Button</button>
</div>



回答2:


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
}



回答3:


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



来源:https://stackoverflow.com/questions/15300234/how-can-i-horizontally-center-a-button-element-in-a-div-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!