Reputation: 967
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.
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 is my inner DIV spilling out of the outer ? How do I fix it without giving fixed dimensions?
Upvotes: 8
Views: 18035
Reputation: 46
You can convert from margin
to padding
, as inner space of element, and assign to #outer.
Then, the result will appear as your expect.
#outer {
position: fixed;
width: 30%;
height: 30%;
background-color: black;
padding: 5px;
}
#inner {
width: 100%;
height: 100%;
background-color: orange;
}
<div id="outer">
<div id="inner">
</div>
</div>
Upvotes: 1
Reputation: 21
What helped me with the same problem is:
position: absolute;
left: 0;
top: 0;
Upvotes: 1
Reputation: 67798
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>
Upvotes: 8
Reputation: 3315
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;
}
Upvotes: 3
Reputation:
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 id="outer">
<div id="inner">
</div>
</div>
</body>
Upvotes: 2
Reputation: 2921
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.
Upvotes: 6
Reputation: 97
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?
Upvotes: 1