Reputation: 177
I have a div inside another div and when I set margin and padding to the inner div it overlaps with parent.
How can I prevent the inner div overlapping?
Here is a fiddle of the below:
.outer {
border: 1px;
border-style: solid;
width: 250px;
height: 250px;
}
.inner {
padding: 5px;
margin: 5px;
height: 100%;
width: 100%;
border: 1px;
border-style: solid;
}
<div class="outer">
<div class="inner">inner</div>
</div>
Upvotes: 1
Views: 5814
Reputation: 305
The inner div
overlaps because you introduced a 5px offset via margin
, yet set its height and width to 100%
, which is the parent's height, 250px.
You can try setting the height and width to 100% - 2 * margin
using CSS3:
.inner {
height:calc(100% - 2 * 5px);
}
Upvotes: 0
Reputation: 4503
margin:5px;
for .inner
padding: 5px
parent .outer
box-sizing
for .inner
- 100% + padding 5px > 100%.outer {
border:1px;
border-style:solid;
width:250px;
height:250px;
padding: 5px;
}
.inner {
padding:5px;
height:100%;
width:100%;
border:1px;
border-style:solid;
box-sizing: border-box;
}
<div class="outer">
<div class="inner">inner</div>
</div>
Upvotes: 2
Reputation: 2309
Method 1: Try position:relative for the parent div and position:absolute for the inner div and add 5px each to the top,left,bottom and right, to push it from all sides:
.outer {
border:1px;
border-style:solid;
width:250px;
height:250px;
overflow:hidden;
position:relative;
}
.inner {
padding:5px;
left:5px;
top:5px;
bottom:5px;
right:5px;
position:absolute;
border:1px;
border-style:solid;
}
Fiddle: http://jsfiddle.net/7kcaavzt/2/
Method 2 Add display:table to the parent div and add 5px padding to it than adding margin to the inner div.
Fiddle: http://jsfiddle.net/7kcaavzt/4/
Upvotes: 3