简体   繁体   English

如何在 div 元素中水平居中按钮元素?

[英]How can I horizontally center a button element in a div element?

I don't want to add CSS to my div element (eg <div style="text-align: center;"> ).我不想将 CSS 添加到我的 div 元素(例如<div style="text-align: center;"> )。

I only want to add CSS code to the button element.我只想向按钮元素添加 CSS 代码。

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

How can I center the button horizontally in this case?在这种情况下,如何将按钮水平居中?

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

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

You need display: block; margin: auto;你需要display: block; margin: auto; display: block; margin: auto; on the <button> .<button> jsFiddle js小提琴

Others have already mentioned the margin: 0 auto;其他人已经提到了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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM