Fit Image in Container

CSSCSSBeginner
Practice Now

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

Introduction

In this lab, we will learn how to use CSS to fit and position images within their containers while preserving their aspect ratio. We will explore the object-fit and object-position properties and how they can be used to achieve different results. By the end of this lab, you will be able to create visually appealing images that fit perfectly within their designated space.


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/borders("`Borders`") css/CoreLayoutGroup -.-> css/width_and_height("`Width and Height`") css/CoreLayoutGroup -.-> css/positioning("`Positioning`") css/IntermediateStylingGroup -.-> css/backgrounds("`Backgrounds`") subgraph Lab Skills css/selectors -.-> lab-35197{{"`Fit Image in Container`"}} css/colors -.-> lab-35197{{"`Fit Image in Container`"}} css/borders -.-> lab-35197{{"`Fit Image in Container`"}} css/width_and_height -.-> lab-35197{{"`Fit Image in Container`"}} css/positioning -.-> lab-35197{{"`Fit Image in Container`"}} css/backgrounds -.-> lab-35197{{"`Fit Image in Container`"}} end

Fit Image in Container

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

To fit an image inside its container while preserving its aspect ratio, you can use object-fit: contain. To fill the container with the image while preserving its aspect ratio, use object-fit: cover. If you want to position the image at the center of the container, you can use object-position: center.

Here's an example of how you can use these properties:

<img class="image image-contain" src="https://picsum.photos/600/200" />
<img class="image image-cover" src="https://picsum.photos/600/200" />

And the corresponding CSS:

.image {
  background: #34495e;
  border: 1px solid #34495e;
  width: 200px;
  height: 200px;
}

.image-contain {
  object-fit: contain;
  object-position: center;
}

.image-cover {
  object-fit: cover;
  object-position: right top;
}

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 Fit Image in Container lab. You can practice more labs in LabEx to improve your skills.

Other CSS Tutorials you may like