2016-10-26 74 views
2

#outer#inner必须都是position:absolutefixed绝对定位的子元素溢出父容器

如何可以有这样的,使得在所述#inner100%值是相对于#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

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. 计算孩子的宽度和高度以模拟父级上的20px填充。
  3. 垂直居中元素
  4. 水平居中元素
  5. Make vertical and horizontal centering precise.
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>

相关问题