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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15300234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:15:13  来源:igfitidea点击:

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

htmlcsscentertext-alignmenttext-align

提问by weilou

I don't want to add CSS to my div element (e.g. <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?

在这种情况下,如何将按钮水平居中?

回答by j08691

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

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

回答by Phillip Schmidt

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.

其他人已经提到了该margin: 0 auto;方法,但是如果您想解释一下,浏览器会在您的元素所在的任何容器中拆分可用空间。

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
}

回答by dezman

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

您需要display: block; margin: auto;<button>. js小提琴