1

I have a rectangular image and I would like to crop it into square. It's something like this:

img {
    width:  200px;
    height: 200px;
}

It works great, but only when I know final width and height. But what I should do when I don't know height value, only width and not in px but in %?

img {
    width: 25%;
}

I have only width (25%) and I need square image. What should I do?

I need solution in CSS. I can't use JS.

ZaquPL
  • 789
  • 2
  • 12
  • 28
  • possible duplicate : http://stackoverflow.com/questions/5445491/height-equal-to-dynamic-width-css-fluid-layout – webNeat Aug 28 '14 at 15:15
  • possible duplicate of [CSS Display an Image Resized and Cropped](http://stackoverflow.com/questions/493296/css-display-an-image-resized-and-cropped) – MikeSmithDev Aug 28 '14 at 15:19

1 Answers1

3

If it doesn't need to be an img then I would create a div, make the image the background-image, force a pseudo element to make the height relative to the width of the div and then make the background image cover the div with background-size:

http://jsfiddle.net/8tqxvvzs/

div
{
    position: relative;
    display: block;
    background-image: url('http://placehold.it/350x150');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
    width: 25%;
}

div:before
{
    content: "";
    display: block;
    padding-top: 100%;
}
Luke
  • 3,985
  • 1
  • 20
  • 35