【问题标题】:Absolute position inside relative position, element goes over parent's width?相对位置内的绝对位置,元素超出父级的宽度?
【发布时间】:2012-05-14 23:18:40
【问题描述】:

请参考小提琴:http://jsfiddle.net/ukzKT/8/

我希望内部 div #this-bottom 保持在底部,但它的宽度应该与其中的任何其他 div 一样。即它应该保持在父 div #top 的填充区域内。

CSS

#top{
    width:300px;
    position:relative;
    padding:20px;
    border:1px solid #222;
}
#this-bottom{
    position:absolute;
    bottom:0;
    border:1px solid #333;
    right: 18px;
    left: 20px;
}
#other{
    width:100%;
    border:1px solid #333;
}

HTML

<div id='top'>
    <div id='other'>
        This is 1 <br />
        THis is 2 <br />
        This is 3 <br />

    </div>
    <div id='this-bottom'>
        This should be bottom
    </div>
</div>

【问题讨论】:

  • 当您没有定义 CSS 时,为什么会出现这种行为?
  • @Diodeus 对不起(错误的小提琴)。现在检查。
  • @ShahalTharique 你的css没有问题,超过父宽度是正常的,因为你使用的是padding:20;
  • @mgraph 是的,我知道.. 任何解决方法?

标签: html css


【解决方案1】:

div 超出父级的原因是 width100%left 被分配了默认值('auto') - 在这种情况下是 20px 由于padding。所以div 将在父容器之外流动20px

要阻止这种情况发生,您可以设置left: 20pxright: 20px(与填充相同)并删除width: 100%

【讨论】:

  • 其实不是猜测;)只要不定义4个方向中的任何一个,就取元素原始值。
  • @Christoph - 谢谢,你是对的,我已经更新了我的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 2021-12-29
  • 2018-06-20
  • 2011-09-23
相关资源
最近更新 更多