Constant Width to Height Ratio

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to create a constant width to height ratio for elements with varying widths. By using the padding-top property on a ::before pseudo-element, we can ensure that the height of the element remains proportionate to its width. This technique can be used to create responsive squares and other shapes with specific aspect ratios.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 97% completion rate. It has received a 100% positive review rate from learners.

Constant Width to Height Ratio

index.html and style.css have already been provided in the VM.

This code snippet ensures that an element with variable width will retain a proportionate height value. To achieve this, 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 with a 1:1 ratio. To use this code, simply add the following HTML code:

<div class="constant-width-to-height-ratio"></div>

Then, add the following CSS code:

.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;
}

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Constant Width to Height Ratio lab. You can practice more labs in LabEx to improve your skills.