I need my child div to stick to the bottom of the parent div, hence the position: absolute
and bottom: 0px
. I also need the child width to be the same as the parent, and I thought box-sizing: border-box
would work, but the width of the child still protrudes to the right, due to the padding and margins.
How do I fix this?
.parent {
height: 500px;
min-width: 500px;
position: relative;
background-color: red;
}
.child {
padding: 10px 10px 10px 10px;
margin: 10px 10px;
background-color: grey;
bottom: 0px;
box-sizing: border-box;
position: absolute;
width: 100%;
}
<div class="parent">
<div class="child"></div>
</div>
View on JSFiddle
Use left:0
/right:0
instead of width:100%
to avoid overflow due to margin as actually your element is taking 500px + 20px(of margin left/right) inside the parent element.
As a side note, box-sizing: border-box
is working perfectly but inside the element so padding are included in the width but margin of course not:
border-box tells the browser to account for any border and padding in the values you specify for width and height ... ref
.parent {
height: 500px;
min-width: 500px;
position: relative;
background-color: red;
}
.child {
padding: 10px 10px 10px 10px;
margin: 10px 10px;
background-color: grey;
bottom: 0px;
box-sizing: border-box;
position: absolute;
left: 0;
right: 0;
}
<div class="parent">
<div class="child" ></div>
</div>
You thinking was correct. margin property moves elements from its original with the help of left, top, right and bottom. More importantly, margin does not obey container boundary restriction.
Please check the below code. To contain the child within the parent container, you should reduce the total width of the child if you like to keep margin margin-left and margin-right properties.
CSS3 calc is so smart in working with two different units. calc(100% - 20px)
will give you the correct width which will contain child element inside parent element.
.parent {
height: 500px;
min-width: 500px;
position: relative;
background-color: red;
}
.child {
padding: 10px 10px 10px 10px;
margin: 10px 10px;
background-color: grey;
bottom: 0px;
box-sizing: border-box;
position: absolute;
width: calc(100% - 20px); //Subtracting left and right margin from the total width to avoid overflowing the parent container
}
<div class="parent">
<div class="child">
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With