Why does inner DIV spill out of outer DIV?

I have been long away from HTML and CSS, can't find the 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> <div> </div> </div>

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

2

5 Answers

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> <div> </div> </div>
0

The answers above assume that you do not want the margin. If you, in fact, want the margins, then you can add overflow: hidden; to the #outer.

You can set #inner in position absolute and instead of using margin, you can use this

#inner { position: absolute; top: 5px; bottom:5px; left:5px; right:5px; background-color: orange; } 
body { width: 100%; height: 1000px; } #outer { position: fixed; width: 30%; height: 30%; background-color: black; } #inner { position: absolute; top: 5px; bottom:5px; left:5px; right:5px; background-color: orange; }
<body> <div> <div> </div> </div> </body>

The margin property moves the div by 5 pixels from both top and left direction, and since divs have overflow: show; as default (which means any content that goes outside the div will be shown) you can see the div going outside.

you can avoid that using overflow: hidden; to hide any content going outside the div, if that's what you want to do otherwise you need to set your inner div size in a way that doesn't go outside its container

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

This is likely happening because your inner div is being pushed out of its parent by the margin. Have you tried setting 'inner' to position: absolute with left: 0 and top: 0 property?

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like