4

#outer and #inner must both be position:absolute or fixed.

How can I have this so that the 100% values in #inner are relative to #outer's width minus its padding (e.g., like a frame) and not have #inner overflow?

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

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Nick
  • 63
  • 4

2 Answers2

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>

Notes:

  1. Padding on parent element will be ignored by the child, which is absolutely positioned and, therefore, removed from the document flow. Adjust the size of the child instead to achieve a similar effect.
  2. Width and height of child is calculated to emulate 20px padding on the parent.
  3. Vertically center element
  4. Horizontally center element
  5. Make vertical and horizontal centering precise.
Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
1

Slightly less complicated code, although it uses flex-box, which isn't working in older browsers.

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>
junkfoodjunkie
  • 3,168
  • 1
  • 19
  • 33