如何在父div中修复子div位置

时间:2015-09-16 08:19:01

标签: css

我想我的孩子div将在父div中显示相同的位置(绝对)和相同的填充(20px)。如果我相对于子div放置位置然后它将进入父div,但我想使用绝对位置到子div,但是当我运行此代码时子div超出父div。

.parent {
  border:1px solid black;
  height:100px;
  padding:20px;
  position: relative;
  width:400px;
}
.child {
  border:1px solid red;
  height:50px;
  position:absolute;
  width:100%;
}

4 个答案:

答案 0 :(得分:0)

只需设置子div宽度属性即可继承,它将完美运行。

.parent { border:1px solid black; height:100px; padding:20px; position:   relative; width:500px;} 
    .child { border:1px solid red; height:50px; position: absolute; width: inherit;} 

答案 1 :(得分:0)

width%计算整个宽度,包括边框和填充。 所以我们需要的是宽度= 400 - (20×2)(填充)= 360即90%。

.parent { border:1px solid black; height:100px; padding:20px; position: relative; width:400px; }
.child { border:1px solid red; height:50px; position:absolute; display:block;width:90%;}

答案 2 :(得分:0)

只需将其添加到子div。

width: inherit;

答案 3 :(得分:-1)

如果你想要它尊重父母(即接受20px填充),不要绝对定位它