【问题标题】:Align text to center in div with another div as percentage background将文本与另一个 div 作为百分比背景在 div 中居中对齐
【发布时间】:2012-12-27 15:23:27
【问题描述】:

情况:我有一个 div,它是其父级的 100% 宽度。这个div中有文字需要居中/

此外,在该 div 中,我还有另一个元素,它应该具有外部 div 宽度的百分比,无论是 0 到 100%(该区域将设置背景颜色)。

代码可能类似于:

<div style="text-align:center; width:100%;">40%
    <div style="background-color: green; width:40%;"></div>
</div>

所以我希望文本 '40%' 居中,并且外部 div 的 40% 的左侧将具有绿色背景色。

我做错了什么?

谢谢。

【问题讨论】:

  • 第二个div中的错误附加样式格式在询问之前先检查问题.....

标签: html css alignment


【解决方案1】:
<div style="text-align:center; width:100%;position: relative;">40%
    <div style="background-color: green; width:40%;position: absolute;top: 0px;left: 0px; height: 100%;"></div>
</div>

您需要在外部div 上设置position: relative 以确保内部div 相对于它定位 您需要在内部div上设置position: absolute,并将其topleft设置为0,将widthheight设置为100%

另外,您在第二个div 中遗漏了style="

【讨论】:

    【解决方案2】:
    <div style="text-align:center; width:100%;">40%
        <div style="background-color: green; width:40%; margin:0 auto;">40%</div>
    </div>​​​​​​​​​​​​​​​​​​
    

    Working Fiddle

    【讨论】:

      【解决方案3】:
      <div style="text-align:center; width:100%;">40%
      <div style="background-color: green; width:40%;"></div>
      </div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-05
        • 2011-10-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 2013-02-09
        • 1970-01-01
        相关资源
        最近更新 更多