Html 水平对齐按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10935878/
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 00:53:30  来源:igfitidea点击:

Horizontally aligning button

htmlcssbutton

提问by James Dawson

I'm trying to horizontally align a button using CSS. Here's my markup:

我正在尝试使用 CSS 水平对齐按钮。这是我的标记:

<button type="button" class="primary-button download-button">Download</button>

And my relevant CSS:

和我相关的 CSS:

.primary-button {
    font-family: Arial, sans-serif;
    font-size: 1.3em;
    color: #fff;
    border: 1px solid #004487;
    background-image: -webkit-gradient(linear, top, bottom, from(#5288bd), to(#2f659a));
    background-image: -webkit-linear-gradient(top, #5288bd, #2f659a);
    box-shadow: inset 0px 1px 0px rgba(255, 255, 255, 0.4), inset 0px 0px 0px 1px rgba(255, 255, 255, 0.2), 0px 1px 0px rgba(255, 255, 255, .7);
    text-shadow: 0px -1px 0px black;
    cursor: pointer;
}

.download-button {
    padding: 10px 20px;
    border-radius: 5px;
    display: block;
    margin: 10px auto 0px auto;
}

However, it's still aligned to the left. I thought setting margin: 10px auto 0px auto;would horizontally align it seen as it's now a block element but apparently not.

但是,它仍然与左侧对齐。我认为设置margin: 10px auto 0px auto;会水平对齐它,因为它现在是一个块元素,但显然不是。

I've also tried wrapping it in a div and using text-align: centerbut that doesn't work either.

我也试过将它包装在一个 div 中并使用,text-align: center但这也不起作用。

采纳答案by j08691

Give the button a width. See this jsFiddle example.

给按钮一个宽度。请参阅此jsFiddle 示例。

.download-button {
? ? padding: 10px 20px;
? ? border-radius: 5px;
? ? display: block;
? ? width: 130px;
? ? margin: 10px auto 0px auto;
}?

Without a width, you're trying to center a block level element that is the full width of it's container. By explicitly setting a width (for example 130px on your button) the margin centering rule works.

没有宽度,您试图将块级元素居中,该元素是其容器的全宽。通过明确设置宽度(例如按钮上的 130 像素),边距居中规则有效。

回答by TrySpace

Actually setting floatto noneif both have position: relativeshould work:

实际上设置floatnoneif 两者都position: relative应该工作:

.container{
  text-align: center;
 }
.button{
  float: none;
}