Home >Web Front-end >CSS Tutorial >How Can I Achieve the 'background-size: cover' and 'background-size: contain' Effect on Images Using HTML and CSS?

How Can I Achieve the 'background-size: cover' and 'background-size: contain' Effect on Images Using HTML and CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 07:16:35817browse

How Can I Achieve the

Displaying Images with Properties Equivalent to "background-size: cover" and "background-size: contain"

Your concern arises from the desire to display images within HTML documents with the same properties as the "background-size: cover" CSS property for background images. You've experimented with "width: 100%" and "width: auto" styles for images within div elements, but encountered limitations in responsiveness and unwanted behavior due to screen size variations.

Solution #1: object-fit Property (Limited Browser Support)

The "object-fit" property is designed specifically for this purpose. By setting "object-fit: cover;" on the img element, you can achieve the desired behavior, causing the image to fill the available space while maintaining its aspect ratio. However, it's important to note that this property is not supported by Internet Explorer.

Example:

body {
  margin: 0;
}
img {
  display: block;
  width: 100vw;
  height: 100vh;
  object-fit: cover; /* or object-fit: contain; */
}
<img src="https://loremflickr.com/1500/1000" alt="A random image from Flickr" />

The above is the detailed content of How Can I Achieve the 'background-size: cover' and 'background-size: contain' Effect on Images Using HTML and 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