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?
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!