简体   繁体   English

如何使用CSS将按钮居中而不使用div

[英]How to center a button WITHOUT a div using CSS

I am trying to center a button without a div. 我试图将没有 div的按钮居中。 The button is as follows 该按钮如下

<body>
  <button>Some Text</button>
</body>

I have tried using a few different techniques such as: 我尝试使用一些不同的技术,例如:

text-align: center

and

margin:0 auto; 

but these don't work. 但是这些不起作用。

Its simple, just make it display as a block element: 它很简单,只需使其显示为块元素即可:

<body>
  <button>Some Text</button>
</body>

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

http://jsfiddle.net/df216mho/ http://jsfiddle.net/df216mho/

Try this (You dont need a extra div or set a width) 试试这个(您不需要额外的div或设置宽度)

CSS 的CSS

button{
position: relative;
display: inline-block;
left: 50%;
transform: translateX(-50%);
}

DEMO HERE 此处演示

Use this. 用这个。 It works: 有用:

<body>
  <button style="position: relative; left: 50%;" >Some Text</button>
</body>

I used inline CSS since its easier to show on here. 我使用内联CSS,因为它更容易在此处显示。

If you use a set width then margin: 0 auto; 如果使用设定的宽度,则margin: 0 auto; will work. 将工作。

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

The reason you do not need to set a width for a <button> with margin: 0 auto; 不需要为<button>设置宽度的原因是margin: 0 auto; when you also set it to display: block; 当您还将其设置为display: block; is that a <button> is a replaced element. <button>是被替换的元素。 Basically they are elements that have a predetermined width and height without the use of CSS. 基本上,它们是不使用CSS即可具有预定宽度和高度的元素。

Checkout this SO answer provided by @Brewal for a few more details. 查看@Brewal提供的SO答案 ,以获取更多详细信息。

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

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