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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay