Introduction
In this lab, we will learn how to create a responsive container with a specified aspect ratio using CSS. You will be introduced to the --aspect-ratio custom property and how to use the calc() function to calculate the container's height. You will also learn how to set the child element to maintain the aspect ratio using the object-fit: cover property. By the end of this lab, you will have a better understanding of how to create visually appealing and responsive containers on your web pages.
Aspect Ratio
index.html and style.css have already been provided in the VM.
This code creates a responsive container with a specific aspect ratio using CSS custom properties and calc() function. Follow these steps to achieve this:
- Define the desired aspect ratio using a CSS custom property,
--aspect-ratio. - Set the container element's
positionproperty torelativeand itsheightproperty to0. - Calculate the container element's height using the
calc()function and the--aspect-ratiocustom property, and set it as thepadding-bottomproperty. - Set the direct child of the container element to
position: absolute,top: 0,left: 0,width: 100%, andheight: 100%. - Maintain the aspect ratio of the child element by setting its
object-fitproperty tocover.
Use the following HTML and CSS code to create the container:
<div class="container">
<img src="https://picsum.photos/id/119/800/450" />
</div>
.container {
--aspect-ratio: 16/9;
position: relative;
height: 0;
padding-bottom: calc(100% / var(--aspect-ratio));
}
.container > * {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
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 Aspect Ratio lab. You can practice more labs in LabEx to improve your skills.