【问题标题】:how do you set the width of an absolutely positioned div to 100% of its parent?如何将绝对定位的 div 的宽度设置为其父级的 100%?
【发布时间】:2011-12-08 08:51:59
【问题描述】:

给定以下代码

<!DOCTYPE html>
<html>
  <head>
    <title>show stats</title>
    <style>
    span.main {
        position:relative;
        display:inline-block;
    }
    div.stats {
        position:absolute;
        bottom:50px;
        background:black;
        color:white;
        padding:0px 15px 0px 15px;
        font-weight:500;
    }
    </style>
  </head>

  <body>

    <span class="main">
      <img src="http://i.imgur.com/o2udo.jpg" alt="test" title="testpic"/>
      <div class="stats">
        <p>this is a caption</p>
      </div>
    </span>
    <span class="main">
      <img src="http://i.imgur.com/o2udo.jpg" alt="test" title="testpic"/>
      <div class="stats">
        <p>this is a caption</p>
      </div>
    </span>
    <span class="main">
      <img src="http://i.imgur.com/o2udo.jpg" alt="test" title="testpic"/>
      <div class="stats">
        <p>this is a caption</p>
      </div>
    </span>

  </body>

</html>

我想让 div.stats 成为包含 span.main 的宽度。将宽度设置为 100% 不起作用,因为生成的宽度超出容器宽度的内边距量 (30px)。

我可以通过将 div.stats 的填充设置为 0,然后填充此 div 内的段落来修复它。这似乎可行,但我怀疑我这样做的方式很愚蠢。有没有更简洁的方法来将此 div 定位在其容器的宽度上,同时保持其垂直位置?

【问题讨论】:

    标签: html css


    【解决方案1】:

    left:0right: 0 添加到div.stats

    div.stats {
        position:absolute;
        bottom:50px;
        background:black;
        color:white;
        padding:0px 15px 0px 15px;
        font-weight:500;
        left: 0;       /*Add this*/
        right: 0;      /*Add this*/
    }
    

    JSFiddle:http://jsfiddle.net/sT9vA/1/

    【讨论】:

      猜你喜欢
      • 2017-06-03
      • 1970-01-01
      • 2023-03-26
      • 2020-12-06
      • 1970-01-01
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多