Aspect Ratio
The aspect-ratio
is like a picture frame that maintains the ratio between the width and height of an image.
By using this property, you can ensure that the desired aspect ratio is maintained when resizing elements.
Code Example
.box { width: 100px; /* Width */ aspect-ratio: 16 / 9; /* 16:9 Aspect Ratio */ background-color: lightblue; }
An element with the .box
class will have its width set to 100px and its height will automatically be 56.25px (100 / 16 * 9)
, maintaining a 16:9 aspect ratio.
object-fit Property
The object-fit
property is like deciding how to place a photo into a photo album.
object-fit: cover (crop if the image is too large)
Scale the content to fill the container while maintaining the content's aspect ratio.
If the content's aspect ratio differs from the container's, the excess parts are cropped.
object-fit: none (center if the image is too small)
Maintain the original size of the content without any resizing.
It is displayed at its original size irrespective of the container's size, typically centered.
object-fit: contain (keep aspect ratio and fill the album entirely)
Scale the content to fit within the container while keeping the aspect ratio.
If the content doesn't entirely fill the container, padding or margin space appears.
Code Example
.image { width: 300px; height: 200px; object-fit: cover; }
An image with the .image
class will maintain its original aspect ratio while fully occupying a 300px * 200px
rectangle.
Any parts that exceed the container are cropped.
Follow the highlighted sections of the code to try it out.
Which value of the object-fit
property maintains the aspect ratio of the content?
cover
contain
none
fill
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help