【问题标题】:Is the property text-align: center; a good way to center a div using CSS?是属性 text-align: center;使用 CSS 使 div 居中的好方法?
【发布时间】:2014-10-02 08:43:01
【问题描述】:

我需要使一个 div 相对于其周围的 div 容器居中。我要居中的 div 包含一个广告投放 javascript 代码 sn-p。我可以使用 text-align: center 来使 div 居中,如下所示?这符合 W3C 标准吗?

这是广告投放的 javascript:

<div id="testadunit" style="text-align: center;">
<!-- below is the ad tag -->
<script type="text/javascript">
//<![CDATA[
adxpro_key = "a1300082f3da7cdbc1d61e8399484798";
adxpro_channel = "";
adxpro_code_format = "ads";
adxpro_ads_host = "//adxpro.net";
adxpro_click = "";
adxpro_custom_params = {};
adxpro_width = "180";
adxpro_height = "150";

document.write("<script type='text\/javascript' src='"+(location.protocol == 'https:' ? 'https:' : 'http:') + "//adxpro.net\/js/show_ads_adxpro.js'><\/script>");
//]]>
</script>
<!-- End ad tag -->
</div>

【问题讨论】:

    标签: centering text-align


    【解决方案1】:

    最好的方法实际上是使用以下 css:

    margin-left:auto;
    margin-right:auto;
    

    除了旧版本的 InternetExplorer 不能使用“自动”,因此很遗憾,您可能不得不为这些版本的浏览器保留 text-align:center。

    【讨论】:

      【解决方案2】:

      text-align: center 不会使 div 居中,除非该 div 已设置为 inline 或 inline-block。您上面的代码不会以 div 为中心,而是以 div 中的文本为中心。 @IronWilliamCash 有正确的答案:将左右边距设置为 auto 并且 div 将在其父容器中居中。我相信旧版本的 IE 也不支持将 div 设置为 inline 或 inline-block。

      就 W3C 标准而言,不知道。

      【讨论】:

        猜你喜欢
        • 2021-07-01
        • 1970-01-01
        • 2019-10-24
        • 2012-03-18
        • 2018-07-01
        • 1970-01-01
        • 2013-11-04
        • 2021-04-15
        • 2012-06-06
        相关资源
        最近更新 更多