object fit cover for img tag i want position it in css without background position
To position the object fit cover for an img tag using CSS without background position, you can use the following code:
HTML:
<img src="image.jpg" class="cover">
CSS:
.cover {
width: 300px;
height: 200px;
object-fit: cover;
position: relative;
}
.cover:before {
content: "";
display: block;
padding-top: 66.6667%;
}
.cover img {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
object-fit: cover;
}
Explanation:
- The
.coverclass is applied to the img tag and sets the width, height, and object-fit properties. The position property is set to relative to allow positioning of child elements. - The
.cover:beforepseudo-element is used to create a placeholder for the image. It sets the padding-top property to a percentage value that maintains the aspect ratio of the image (in this case, a 3:2 aspect ratio). This ensures that the container maintains the correct aspect ratio even if the image is not loaded or fails to load. - The
.cover imgselector targets the actual image element inside the container. It is positioned absolutely and set to the top-left corner of the container with a height and width of 100%. The object-fit property is set to cover to ensure that the image fills the container while maintaining its aspect ratio.
Note: This method may not be compatible with older browsers
原文地址: https://www.cveoy.top/t/topic/eFAU 著作权归作者所有。请勿转载和采集!