Have you ever used padding-top: 10%?


Front-End Development

If you've been working with the front-end for a while you've probably seen something like padding-top: 10% or margin-bottom: 20%; Personally I haven't used it much but I see these properties every now and then. But have you ever wondered how to calculate these values?

It seems like a simple question. For example let's have a wrapper div with the 200px height and 500px width. Inside that div lets put another inner div with the 50x50px width and height. Cool! So now we have something like this:

Inner div screenshot

Now lets give that inner div a margin-top: 10%; What would happen to it? It seems pretty easy. 10% to 200px height is 20px so our inner div would have a 20px margin-top. Wrong! In reality we end up with such result:

margin top 50px div

It turns out that giving our inner div margin-top: 10% we moved it down by 50px instead of 20px. The reason for this is that the margin / padding percentage height is being calculated by the width of the parent container. So 10% to 500px parent width ends up as 50px. It can be surprising to someone but it's good to know.

The reason for this I guess is that you can't always know the hight of the parent container so the width is used instead. But can this method really be useful? Actually yes. For example when you need to resize the embedded video and keeping the proportions.


Ratio for videos

This time we will use padding in percentages which of course will be based on the width of the containing container. These are the styles I'll be using:

css styles percentage padding

As you can see I am using the main container for the video - video-block and the video wrapper block - video-wrapper. Inside it I have a typical iframe. The one that youtube gives us. And that's pretty much it.

css styles percentage padding markup


Mainly I use video-block only for defining the width of the video container. It is just a wrapper of the block.

As to video-wrapper itself. I've used padding-bottom: 56.25% since this is the 16:9 ratio. Just divide 9 to 16. Other styles are mostly for styling purposes and support. For example height: 0 is for the IE mainly. You could skip it in Chrome.

The same goes for the iframe styles. We use 100% height and width to make it stretch to fill the width and height of the parent container. And top and left zero to position the box accordingly. Here is the real example of the video from the youtube. If you resize the browser slowly you'll see the video proportionally changes size.


You can play around with it even more, but this was just a real life good example of how we can use percentage margins and paddings like we just did in our example using padding-bottom: 56.25%.