HTML-CSS: Fit image in container
HTML-CSS : Exercise-38 with Solution
Using HTML, CSS fits an positions an image appropriately inside its container while preserving its aspect ratio.
- Use object-fit: contain to fit the entire image within the container while preserving its aspect ratio.
- Use object-fit: cover to fill the container with the image while preserving its aspect ratio.
- Use object-position: center to position the image at the center of the container.
HTML Code:
<!--License: https://bit.ly/3GjrtVF--><!-- Comment: Indicates the license information for the code -->
<!DOCTYPE html><!-- Comment: Declares the document type and version of HTML -->
<html><!-- Comment: Indicates the start of the HTML document -->
<head><!-- Comment: Contains meta-information about the HTML document -->
<meta charset="utf-8"><!-- Comment: Declares the character encoding for the document -->
<meta name="viewport" content="width=device-width"><!-- Comment: Sets the viewport width to the width of the device -->
<title>Using HTML, CSS fits an positions an image appropriately inside its container while preserving its aspect ratio</title><!-- Comment: Sets the title of the document -->
</head><!-- Comment: End of the head section -->
<body><!-- Comment: Contains the content of the HTML document -->
<img class="image image-contain" src="https://www.w3resource.com/html-css-exercise/html-css-practical-exercises/flower-9.jpeg" /><!-- Comment: Inserts an image with class "image-contain" and sets its source -->
<img class="image image-cover" src="https://www.w3resource.com/html-css-exercise/html-css-practical-exercises/flower-9.jpeg" /><!-- Comment: Inserts an image with class "image-cover" and sets its source -->
</body><!-- Comment: End of the body section -->
</html><!-- Comment: End of the HTML document -->
Explanation:
CSS Code: Explanation: HTML-CSS Editor:
See the Pen
html-css-practical-exercises by w3resource (@w3resource)
on CodePen.
.image {
background: #34495e; /* Comment: Sets the background color of the image */
border: 1px solid #34495e; /* Comment: Sets a solid border around the image */
width: 200px; /* Comment: Sets the width of the image */
height: 200px; /* Comment: Sets the height of the image */
}
.image-contain {
object-fit: contain; /* Comment: Specifies how the image should fit inside its container */
object-position: center; /* Comment: Specifies the position of the image inside its container */
}
.image-cover {
object-fit: cover; /* Comment: Specifies how the image should cover its container */
object-position: right top; /* Comment: Specifies the position of the image inside its container */
}
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics