In this blog we will be talking about a common issue most developers have come across when working with CSS. Yep, the issue of having a child HTML element overlap a parent element when the width of it is set to 100%.
It is quite annoying coming across this issue as you really just want the element to fill the container, why can't it be that simple?
Well I am about to tell you why.
The width or height of any element inside a container is calculated using more than just the height or width. There are some other CSS property values that are included that form part of the total width of the child element if they are included in your styles.
These are the other CSS properties that can affect the length of your child element.
- border-width
- padding
In this example let us just focus on the "width" CSS property along with border-width and padding.
Let's consider this styling for the parent and child elements.
The below is a representation of the above styling.
100% + border-right-width + border-left-width + padding-left + padding-right
Which is WAY above 100%, so the overflow makes sense.
Luckily you can fix this behaviour. The CSS property box-sizing is what we will be looking at.
By default, most elements have the box-sizing value as content-box. But we do not want that. We want to use border-box.
border-box tells that browser to account for the border-width and padding in the width value. Meaning that the values for padding and border-width will now be calculated inside the width property.
Let's see another example using the border-box property this time.
Let's define some new styles.
And there we go!
The child element now fills with the parent while using the set border-width and padding values!
I hope you enjoyed the read. Cheers!