Coder Perfect

How do I use CSS to “crop” a rectangle image into a square?

Problem

I understand that modifying a picture with CSS is impossible, which is why I placed crop in quotes.

What I’d like to do is take rectangular photographs and use CSS to transform them into square images without altering them in any way.

Basically, I’d like to change this around:

Into this:

Asked by novicePrgrmr

Solution #1

A CSS-only method without the usage of a wrapper div or other unnecessary code:

img {
  object-fit: cover;
  width:230px;
  height:230px;
}

Answered by Peter Kionga-Kamau

Solution #2

They don’t have to be in IMG tags, right?

HTML:

<div class="thumb1">
</div>

CSS:

.thumb1 { 
  background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
  width: 250px;
  height: 250px;
}

.thumb1:hover { YOUR HOVER STYLES HERE }

EDIT: If the div requires a link, simply change the HTML and Styles as follows:

HTML:

<div class="thumb1">
<a href="#">Link</a>
</div>

CSS:

.thumb1 { 
  background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
  width: 250px;
  height: 250px;
}

.thumb1 a {
  display: block;
  width: 250px;
  height: 250px;
}

.thumb1 a:hover { YOUR HOVER STYLES HERE }

Note that this might be changed to make it more responsive, such as using percent widths and heights, and so on.

Answered by Michael

Solution #3

For example:

<div style="width:200px;height:200px;overflow:hidden">
    <img src="foo.png" />
</div>

Answered by j08691

Solution #4

If the image is in a responsive-width container:

(edit: sass has been replaced with basic css) (edit: dummy image added for reference)

Answered by JKL

Solution #5

Background-size:cover is used here: http://codepen.io/anon/pen/RNyKzB

CSS:

.image-container {
  background-image: url('http://i.stack.imgur.com/GA6bB.png');
  background-size:cover;
  background-repeat:no-repeat;
  width:250px;
  height:250px;
}  

Markup:

<div class="image-container"></div>

Answered by Philip Nuzhnyy

Post is based on https://stackoverflow.com/questions/15167545/how-to-crop-a-rectangular-image-into-a-square-with-css