保证金权利在宽度上突破100%

时间:2012-03-26 18:09:43

标签: html css position margin

我有一个包含图像和第二个DIV的DIV。父DIV设置为position: absolute;子DIV设置为position: relative。我的想法是在我的图像上显示我的照片标题。

儿童DIV的父级宽度应为100%,左侧,右侧和底部的缩写为10px,加上黑色背景。

.article-container {
  position: relative;
}

.photo-caption {
  width: 100%;
  background-color: black;
  position: absolute;
  bottom: 0px;
  margin-right: 10px;
  margin-left: 10px;
  margin-bottom: 10px;
}
<div class="span15 article-container">
  <img src="images/example-image-1.png" />
  <div class="photo-caption">This is the subtitle text on top.</div>
</div>

左边距在.photo-caption范围之外碰撞.article-container。右边距似乎没有任何影响。

我也试过用box-sizing解决这个问题。似乎将.photo-caption的宽度降低到父宽度,但仍然存在悬垂。

9 个答案:

答案 0 :(得分:23)

最好删除width:100%。写得像这样:

.photo-caption  {
            left:0;
            right:0;
            background-color: black;
            position: absolute;
            bottom: 0px;
            margin-right: 10px;
            margin-left: 10px;
            margin-bottom: 10px;
            }

答案 1 :(得分:15)

绝对定位的元素位于topleftrightbottom,而不是margin

答案 2 :(得分:6)

问题是width=100%photo-caption的确切宽度为article-container;添加边距(或填充)不会影响宽度计算。您可以使用css calc()自行完成此操作,以便样式变为:

.photo-caption  {
    width: calc(100% - 20px); // 20 = right margin + left margin
    background-color: black;
    position: absolute;
    bottom: 0px;
    margin-right: 10px;
    margin-left: 10px;
    margin-bottom: 10px;
}

请注意,您可能需要检查calc()浏览器支持here

答案 3 :(得分:4)

问题在于您将宽度设置为100%,这样就无法留出余量。而是将宽度调整为小于100%的百分比,然后将边距指定为剩余空间百分比的一半。

例如:

style="width:98%; margin-left: 1%;"

答案 4 :(得分:2)

paddingbox-sizing结合使用,或将带有边距的嵌套块放在绝对定位的边距内。

答案 5 :(得分:1)

如果显示块,则不需要宽度:100%。这可能会解决所有这些小问题。

.photo-caption  {
        display:block;
        background-color: black;
        position: absolute;
        bottom: 0px;
        margin-right: 10px;
        margin-left: 10px;
        margin-bottom: 10px;
        padding:10px
        }

答案 6 :(得分:1)

有关:

简单回答:不要试图使用保证金权利。使用'margin-left:xxxpx; ' - 使xxx足够大,以便根据需要向右推动div框(Div Style = box)。不需要小提琴,可以把它准确地放在你想要的地方。

答案 7 :(得分:0)

边距是从每一边到相邻元素的距离或文档的边界。

保证金权利没有意味着它会将元素推向左边。这意味着它将在右侧产生空间。如果下一个元素将会出现,它将在提到的margin -right之后出现。在你的情况下,宽度是100%。没有空间可用于保证金权利。

困惑点: 1)宽度为auto时视觉效果不同。右边生成边距。但是由于缺少宽度属性。宽度可以自由改变。

2)当元素向右浮动时效果相同。

这两个上面提到的要点将考虑到边缘权利的不同形象。

答案 8 :(得分:0)

width: -webkit-fill-available;
相关问题