Constant width to height ratio

OSCC · CSS, Layout · Dec 30, 2020

Ensures that an element with variable width will retain a proportionate height value.

  • Apply padding-top on the :before pseudo-element, making the height of the element equal to a percentage of its width.
  • The proportion of height to width can be altered as necessary. For example a padding-top of 100% will create a responsive square (1:1 ratio).
Preview
<div class="constant-width-to-height-ratio"></div>
.constant-width-to-height-ratio {
  background: #9C27B0;
  width: 50%;
}

.constant-width-to-height-ratio:before {
  content: '';
  padding-top: 100%;
  float: left;
}

.constant-width-to-height-ratio:after {
  content: '';
  display: block;
  clear: both;
}

Would you like to help us improve 30 seconds of code?Take a quick survey

Recommended snippets

  • Clearfix

    CSS, Layout

    Ensures that an element self-clears its children.

  • Box-sizing reset

    CSS, Layout

    Resets the box-model so that width and height are not affected by border or padding.

  • Offscreen

    CSS, Layout

    Hides an element completely (visually and positionally) in the DOM while still allowing it to be accessible.