Constant Width to Height Ratio

CSSCSSBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL css(("`CSS`")) -.-> css/BasicConceptsGroup(["`Basic Concepts`"]) css(("`CSS`")) -.-> css/BasicStylingGroup(["`Basic Styling`"]) css(("`CSS`")) -.-> css/CoreLayoutGroup(["`Core Layout`"]) css(("`CSS`")) -.-> css/IntermediateStylingGroup(["`Intermediate Styling`"]) css/BasicConceptsGroup -.-> css/selectors("`Selectors`") css/BasicStylingGroup -.-> css/colors("`Colors`") css/CoreLayoutGroup -.-> css/width_and_height("`Width and Height`") css/CoreLayoutGroup -.-> css/display_property("`Display Property`") css/IntermediateStylingGroup -.-> css/backgrounds("`Backgrounds`") css/IntermediateStylingGroup -.-> css/pseudo_elements("`Pseudo-elements`") subgraph Lab Skills css/selectors -.-> lab-35183{{"`Constant Width to Height Ratio`"}} css/colors -.-> lab-35183{{"`Constant Width to Height Ratio`"}} css/width_and_height -.-> lab-35183{{"`Constant Width to Height Ratio`"}} css/display_property -.-> lab-35183{{"`Constant Width to Height Ratio`"}} css/backgrounds -.-> lab-35183{{"`Constant Width to Height Ratio`"}} css/pseudo_elements -.-> lab-35183{{"`Constant Width to Height Ratio`"}} end

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.

Other CSS Tutorials you may like