Creating Intrinsic Ratios for Video

The concept

The idea is to create a box with the proper ratio (4:3, 16:9, etc.), then make the video inside that box stretch to fit the dimensions of the box. It’s that simple.

The trick

The padding property is the magic that styles a box with an intrinsic ratio. This is because we’ll set padding in a percentage, based on the width of the containing block.

The CSS rules below illustrate how to style the parent and child to create a “magic wrapper”—a container that proportionally resizes itself depending on the width of its parent.

.wrapper-with-intrinsic-ratio {
    position: relative;
    padding-bottom: 20%;
    height: 0;
}

.element-to-stretch {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: teal;
}

position: relative

By declaring position: relative all child elements will position themselves in relation to this container.

padding-bottom: 20%

This declaration gives the box a specific format. Using 20% for padding makes the height of the box equal to 20% of its width. We specifically chose to use padding-bottom rather than padding-top. This is because IE5 removes the “space” created via padding-top from the flow. In other words, using padding-top: 20% would create the layout we want, but the box would act like an absolutely positioned element, overlapping the next elements in the flow.

height: 0

Specifying a height of 0 gives this element “layout” so that IE5 and IE6 will dimension the inner box properly. To learn more, visit “On having layout.”

Now, let’s consider each declaration within our .element-to-stretch rule.

position: absolute

This frees the element from the height boundary of its parent. This way, it can be positioned over the “padding area.”

top:0

We set top: 0 to position the box near the top of its parent.

left:0

This declaration positions the box near the left side of its parent.

width: 100%

Declaring width: 100% makes the box stretch to fill the width of its container.

height: 100%

This declaration makes the box stretch to fill the height of its container.

background: teal

We apply a color to reveal the layout of the box.