给定以下代码
<!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 放置在其容器的宽度上,同时保持其垂直位置?
最佳答案
将left:0
和right: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/
关于html - 如何将绝对定位的 div 的宽度设置为其父级的 100%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8424755/