I learned something about percentage-based (%) padding
today that I had totally wrong in my head! I always thought that percentage padding was based on the element itself. So if an element is 1,000 pixels wide with padding-top: 50%
, that padding is 500 pixels. It’s weird having top padding based on width, but that’s how it works — but only sorta. The 50% is based on the parent element’s width, not itself. That’s the part that confused me.
The only time I’ve ever messed with percentage padding is to do the aspect ratio boxes trick. The element is of fluid width, but you want to maintain an aspect ratio, hence the percentage padding trick. In that scenario, the width of the element is the width of the parent, so my incorrect mental model just never mattered.
It doesn’t take much to prove it:
See the Pen
% padding is based on parent, not itself by Chris Coyier (@chriscoyier)
on CodePen.
Thanks to Cameron Clark for the email about this:
The difference is moot when you have a block element that expands to fill the width of its parent completely, as in every example used in this article. But when you set any width on the element other than 100%, this misunderstanding will lead to baffling results.
They pointed to this article by Aayush Arora who claims that only 1% of developers knew this.
Wow, guess I am in that 1%. That explains a lot when I played with it in some responsive designs.
Guess that I’m in that 1%. Years of playing around with CSS has finally made a niche for me.
Wow, I honestly was among the vast majority that didn’t know this. Thanks for the info
Yes and the problem occur often when you set a max-width on the child element. It’s why I always use pseudo element for the padding :
.child:after {
content: " ";
display: block;
padding-top: 50%;
}
This behavior is really useful if you want to have something always be the same aspect to the screen width: (say for a header image or as an iFrame wrapper)
You set the div height to 0, width to 100% and padding-bottom to the desired aspect ratio.
Something like this: padding-bottom: calc(100 / (16 / 9)) %
Hey guys. As I am into CSS about 20 years now I am also in that 1%.
That comes from try and error with the CSS and not from copy and paste framework stuff.
I’ve known about this for about 20 years but have had to correct others numerous times :)
The first common mistake is not to know that vertical percentage padding is based on the width of the containing block and the second mistake is thinking that the containing block is the current element :)
Mind you I used to spend a lot of time reading the specs (https://www.w3.org/TR/2011/REC-CSS2-20110607/box.html#padding-properties) which is something I have let slip now that CSS is so vast. ;)
The example was a bit confusing, because it just looks like a small red rectangle next to a large blue rectangle. Add a bit of opacity, so we can see both elements, this would be much easier to understand right away.