user3769778 user3769778 - 6 months ago 15
CSS Question

Why does inner DIV spills out of outer DIV?

I have been long away from HTML CSS, can't find solution to this simple problem.

I have one div inside the other. Outer Black and inner orange.

enter image description here

My HTML and CSS is :



#outer {
position: fixed;
width: 30%;
height: 30%;
background-color: black;
}
#inner {
width: 100%;
height: 100%;
margin: 5px;
background-color: orange;
}

<div id="outer">
<div id="inner">
</div>
</div>





Why my inner DIV is spilling out of Outer ? How do I fix it without giving fixed dimensions?

Answer

(EDITED)

Because of the margin - the width is 100% PLUS the margin. To avoid that, write width: calc(100% - 10px); (= twice the margin.) Same for height.

#outer {
  position: fixed;
  width: 30%;
  height: 30%;
  background-color: black;
}
#inner {

  width: calc(100% - 10px);
  height: calc(100% - 10px);
  margin: 5px;
  background-color: orange;
}
<div id="outer">
  <div id="inner">
  </div>
</div>