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 .cover class 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:before pseudo-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 img selector 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 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录