DEV Community

ktr92
ktr92

Posted on

[html scss] The equivalent to “background-size: cover” for <img> elements

Content images must be made using <img> tags to be able to add “alt” attribute and other advantages. But if you use images of different sizes in the same container, it might not look good. And in that case we need to fill the container with the image.

codepen example: https://codepen.io/ktr92/pen/xxygMrR

Before / After:

Image description

Solution

HTML markup:

<div class="image">
  <img src="path/to/image" alt="">
</div>

Enter fullscreen mode Exit fullscreen mode

SCSS mixin:

img {
  max-width: 100%;
  max-height: 100%;
}

@mixin imagecenter(
  $padding: 100%, // image aspect ratio. It is a square image by default (value = 100%)
  $fill: width // whether images are horizontal or vertical (height or width respectively)
) {
  display: block;
  height: 0;
  padding-top: $padding; 
  position: relative;
  overflow: hidden;

  img {
    position: absolute;

    left: -9999px;
    right: -9999px;
    top: -9999px;
    bottom: -9999px;
    margin: auto;

    @if $fill == width { 
      width: 100%;
      max-height: initial;
      height: initial;
    } @else {
      height: 100%;
      max-width: initial;
      width: initial;
    }
  }
} 
Enter fullscreen mode Exit fullscreen mode

Usage:

.image{
    @include imagecenter(69.5%, width);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)