绝对定位的子元素溢出父容器

4

#outer#inner必须同时为position:absolutefixed

如何使#inner中的100%值相对于#outer的宽度减去其填充(例如,类似于框架)而不会溢出#inner

html, body {
  height: 100%;
  margin: 0;
  width: 100%;
}
#outer {
  background: red;
  height: 50%;
  padding: 20px;
  position: absolute;
  width: 50%;
}
#inner {
  background: yellow;
  height: 100%;
  position: absolute;
  width: 100%;
}
<div id="outer">
  <div id="inner"></div>
</div>

JSFiddle

2个回答

3

html, body {
  height: 100%;
  margin: 0;
}
#outer {
  background: red;
  height: 50%;
  width: 50%;
  /* padding: 20px; */                  /* 1 */
  position: absolute;
}
#inner {
  background: yellow;
  position: absolute;
  height: calc(100% - 20px);           /* 2 */
  width: calc(100% - 20px);            /* 2 */
  top: 50%;                            /* 3 */
  left: 50%;                           /* 4 */
  transform: translate(-50%, -50%);    /* 5 */
}
<div id="outer">
  <div id="inner"></div>
</div>

注:

  1. 父元素的内边距将被子元素所忽略,因为子元素是绝对定位的,因此已从文档流中删除。你需要调整子元素的大小来达到类似的效果。
  2. 子元素的宽度和高度是根据父元素20像素的内边距计算出来的。
  3. 垂直居中元素。
  4. 水平居中元素。
  5. 使垂直和水平居中更加精确。

1
稍微简单一些的代码,虽然使用了弹性盒子布局,但在旧版浏览器中可能无法正常工作。

html, body {
  height: 100%;
  margin: 0;
}
#outer {
  background: red;
  height: 50%;
  width: 50%;
  position: absolute;
  display: flex;
}
#inner {
  box-sizing: border-box;
  background: yellow;
  height: calc(100% - 20px);
  width: calc(100% - 20px);
  margin: auto;
  flex: 0 1 1;
}
<div id="outer">
  <div id="inner"></div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接