I have a component in HTML consisting of 3 nested divs. The overall size of the component is to be controlled by the height and width of the inner div (green). The middle (blue) and outer (red) divs are to wrap the inner div with a 15% gap (so they will both be the same size), so the result should look like this:
To accomplish the gap, I can either:
- add 15% padding to the middle div, or
- add 15% margin to the inner div
However, doing either of these causes the middle and outer divs to expand vertically by 15% but not horizontally. The inner div is still moved to the right by 15% (because of the left-hand padding/margin) but this results in it overflowing the right-hand side of the middle/outer divs.
The following image shows 3 examples:
- No margin/padding, so all 3 divs are (correctly) the same size, i.e. that of the inner div
- The middle div has 15% padding
- The inner div has 15% margin
So how can I force the middle and outer divs to respect the horizontal padding/margin, so it's applied equally to all sides of the inner div?
.outer {
border: red 1px dashed;
display: inline-block;
margin-left: 50px;
/* Just to space the examples out */
}
.middle {
border: blue 1px dashed;
display: block;
}
.inner {
border: forestgreen 1px dashed;
display: block;
height: 100px;
width: 100px;
}
.has-padding {
padding: 15%;
}
.has-margin {
margin: 15%;
}
<div class="outer">
<label class="middle">
<div class="inner"></div>
</label>
</div>
<div class="outer">
<label class="middle has-padding">
<div class="inner"></div>
</label>
</div>
<div class="outer">
<label class="middle">
<div class="inner has-margin"></div>
</label>
</div>