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

时间:2021-03-07 18:55:19

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元素中添加CSS(例如

)。我只想向按钮元素添加CSS代码。

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

How can I center the button horizontally in this case?

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

3 个解决方案

#1


62  

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

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

#2


3  

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.

其他人已经提到边际:0自动;方法,但是如果需要解释,浏览器会将元素所在的容器中的可用空间分割开来。

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


2  

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

你需要显示:块;保证金:汽车;在 <按钮> 。jsFiddle

#1


62  

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

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

#2


3  

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.

其他人已经提到边际:0自动;方法,但是如果需要解释,浏览器会将元素所在的容器中的可用空间分割开来。

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


2  

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

你需要显示:块;保证金:汽车;在 <按钮> 。jsFiddle