CSS 如何在 div 中居中链接元素

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

CSS How to center link elements within a div

css

提问by StevieB

So I have a div which will contain 3 buttons and I want these buttons centered within the div.

所以我有一个包含 3 个按钮的 div,我希望这些按钮在 div 中居中。

I tried this so far

到目前为止我试过这个

.centerButtons  
{
    margin-left: auto;
    margin-right: auto;
    width: 90%;    
}

Which centers the div containing the buttons which is fine, but the actual buttons within this div are not centered..This is my mark up so far..

将包含按钮的 div 居中,这很好,但是这个 div 中的实际按钮没有居中。这是我到目前为止的标记。

<div class="clearfixLeft clearfix centerButtons">
  <xsl:if test="sc:fld('Link One', .)!=''">
    <div class="fl_left mr_7 mt_10">
      <div class="green-btn-solid">
        <sc:link field="Link One">
          <span class="btnspan">
            <sc:text select="." field="Link One Text" />
          </span>
        </sc:link>
      </div>
    </div>
  </xsl:if>
  ...
</div>

Additional Classes

附加课程

/* link styles */
.green-btn-solid {line-height: 21px; height: 21px; background: url(../../images/SOURCE/btn_grn_r.gif) 100% 0 no-repeat; width: auto; display: block; padding-right: 30px; }
.green-btn-solid span {display: block; float: left; background: url(../../images/SOURCE/btn_grn_l.gif) 0 0 no-repeat; line-height: 21px; height: 21px; padding-left: 12px; color: #fff;}

回答by corvid

Have you tried text-align: center;? I'm pretty sure it works on elements as well.

你试过 text-align: center; 吗?我很确定它也适用于元素。

回答by paislee

Use text-align

text-align

.centerButtons {
    text-align: center;
}

which will center all inline children of class centerButtons

这将使班级的所有内联儿童居中 centerButtons

回答by Logan Serman

text-alignon the centerButtonsclass will work if your button is an inline element. If your button is a block-level element, you will need to define it's width and use margin: autolike you did with the centerButtonselement.

text-aligncenterButtons如果您的按钮是内联元素,则该类将起作用。如果您的按钮是块级元素,您将需要定义它的宽度并margin: auto像处理centerButtons元素一样使用。