Home >Web Front-end >CSS Tutorial >How Can I Achieve `background-size: cover` and `background-size: contain` Effects on Image Elements Using CSS?

How Can I Achieve `background-size: cover` and `background-size: contain` Effects on Image Elements Using CSS?

Susan Sarandon
Susan SarandonOriginal
2024-12-14 10:26:11407browse

How Can I Achieve `background-size: cover` and `background-size: contain` Effects on Image Elements Using CSS?

Implementing Background-Size Properties for Image Elements

Modern CSS provides a way to display images in a similar fashion to the background-size: cover and background-size: contain properties for background images.

Solution 1: object-fit Property

For browsers with object-fit support, this property allows for seamless replication of background-size behavior on image elements. Simply add the following CSS to your image:

body {
  margin: 0;
}

img {
  display: block;
  width: 100vw;
  height: 100vh;
  object-fit: cover; /* or object-fit: contain; */
}

The above is the detailed content of How Can I Achieve `background-size: cover` and `background-size: contain` Effects on Image Elements Using CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn