Skip to main content
Practice

Aspect Ratio

aspect-ratio is a property that works like a photo frame, determining the ratio between width and height.

Using this property, you can maintain a desired width-to-height ratio when adjusting the size of an element.


Code Example

CSS
.box {
width: 100px; /* Width */
aspect-ratio: 16 / 9; /* 16:9 Aspect Ratio */
background-color: lightblue;
}

An element with the .box class will have a width of 100px, and its height will automatically be 56.25px (100/16*9), maintaining a 16:9 aspect ratio.


object-fit Property

object-fit works like deciding how to place a photo in a photo album.

  1. Crop the photo if it is too large:

    • object-fit: cover;
    • This value scales the content to fit the container while maintaining the content's aspect ratio. If the content's ratio differs from the container's ratio, the excess part is cropped.
  2. Center the photo if it is too small:

    • object-fit: none;
    • This value keeps the content's size unchanged, displaying it in its original size regardless of the container's size, usually centering it.
  3. Fit the entire photo to fill the album while maintaining ratio:

    • object-fit: contain;
    • This value scales the content to fit the container while maintaining its aspect ratio. If the content doesn't completely fill the container, there will be empty space.

Code Example

CSS
.image {
width: 300px;
height: 200px;
object-fit: cover;
}

An image element with the .image class will fill a 300px by 200px rectangle while maintaining its original aspect ratio.


filter Property

filter works similar to applying filter effects to a photo.

Using the filter property, you can apply various graphic effects to an image or element, such as shadows, transparency, saturation, and brightness.


Code Example

CSS
.filtered-image {
filter: grayscale(100%) blur(3px); /* Grayscale and Blur effect */
}

An element with the .filtered-image class will have a grayscale filter applied, and a slight blur effect with a 3-pixel blur radius.


Follow the highlighted parts in the code and try inputting it yourself.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.