Image tag like background-size: cover

A simple way to let image tags behave to a certain extent like background images with "background-size: cover".

by Simon Harte

HTML

<div class="container technique-1">
  <img src="http://placehold.it/200x200" alt="" />
</div>
<div class="container technique-2">
  <img src="http://placehold.it/200x200" alt="" />
</div>

SCSS

body {
  margin: 0;
}

// width and height can vary for your setup, other styles are just for presentation purposes
.container {
  width: 50vw;
  height: 50vh;
  box-sizing: border-box;
  border: 1px solid black;
  margin: 10px;
}

.technique-1 {
  position: relative;
  overflow: hidden;
  
  img {
    position: absolute;
    top: -9999px;
    right: -9999px;
    bottom: -9999px;
    left: -9999px;
    margin: auto;
    min-width: 100%;
    min-height: 100%;
  }
}

.technique-2 {
  overflow: hidden;
  text-align: center;
  font-size: 0;
  line-height: 0;
  &::before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
  }
  img {
    vertical-align: middle;
    min-width: 100%;
    min-height: 100%;
    margin: -9999px;
  }
}

JavaScript

/**
Different image behaviours can be implemented by changing the width and height values, i.e. by using the following CSS properties in different settings:

- width
- height
- min-width
- min-height
- max-width
- max-height
**/