CSS:我无法将按钮放在DIV元素的中间

13

我正在使用这个教程中的CSS按钮:

http://www.oscaralexander.com/tutorials/how-to-make-sexy-buttons-with-css.html

我需要将一个按钮放在DIV中间使其居中。但是我做不到!

以下是按钮的代码:

<a class="button" href="#"><span>Bring world peace</span></a>  

这里是 CSS:

.clear { /* generic container (i.e. div) for floating buttons */
    overflow: hidden;
    width: 100%;
}

a.button {
    background: transparent url('bg_button_a.gif') no-repeat scroll top right;
    color: #444;
    display: block;
    float: left;
    font: normal 12px arial, sans-serif;
    height: 24px;
    margin-right: 6px;
    padding-right: 18px; /* sliding doors padding */
    text-decoration: none;
}

a.button span {
    background: transparent url('bg_button_span.gif') no-repeat;
    display: block;
    line-height: 14px;
    padding: 5px 0 5px 18px;
} 

这是我正在尝试使用的代码:

<div align="center"><a class="button" href="#"><span>Bring world peace</span></a></div>
3个回答

31

div元素的align属性已被弃用。最好为该div定义一个类,例如:

<div class="centerize">
  <a class="button" href="#"><span>Bring world peace</span></a>
</div>

还有 CSS:

.centerize { 
    text-align: center;
}

需要注意的是,设置文本对齐方式只会影响div内部的内容。div本身应该是一个块级元素,根据其在文档结构中的位置不同,可能本身并不居中。

为了更加确定,您可以尝试像这样做:

.centerize {
    display: block;
    margin: 0 auto;
    text-align: center;
}

现在您可以将 centerize 应用于任何元素,该元素应占用整个浏览器的宽度并居中对齐其内容。


如果有两个按钮,我们想把它们都放在中心,那么这样做可以吗? - kta
我很惊讶,你问这个问题所花费的时间本可以用来尝试一下。在这里,让我为您做一下:http://jsfiddle.net/AUrM8/ - Chris

4

修改这些属性的按钮类:

.button{
  margin-left:50%;
  margin-right:50%;
  position: relative;
}

把你的链接放在 div 中,就像这样:
你的链接
<div align="center">
  <a class="button" href="#"><span>Bring world peace</span></a>  
</div>

谢谢,这只适用于一个单词。当有多于1个单词时,我会得到BRING WORLD PEACE - Alex
@Alex:尝试将 text-align:center 添加到 .button 类和 DIV 中。 - Sarfraz

3

a.button 已向左浮动。您可以在该元素上尝试 float: none;。对于居中对齐元素,margin: 0 auto; 也很有用。


+1. 从按钮中移除浮动。浮动元素会从正常页面布局中移除,因此不受其父元素的布局样式影响。 - Chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接