Question

http://jsfiddle.net/6rwUC/3/

As you can see on the jsfiddle link, I'm trying to create one layout for image previews. I would like to have resized images keeping original ratio, just cut off what overlays the parent div. How can I do this ?

.image-column {
background: #cecece;
width: 100%;
height: 180px;
overflow: hidden;}

.image-column a img {
position:relative;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;}
Was it helpful?

Solution

If CSS3 is an option, you could use transform with a negative translate of -50% horizontally and vertically, while the element is positioned with left: 50% and top: 50% as follows:

.image-column a img {
    position:relative;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

WORKING DEMO.

Update

According to your update:

I would like to have resized images keeping original ratio, just cut off what overlays the parent div.

The only pure CSS solution is using the images as background-image for the <a> elements, while you're using background-size: cover;:

<div class="image-column">
    <a href="#"></a>
</div>
.image-column a {
    display: block;
    height: 100%;
    background: url(http://domain.com/path/to/image.jpg) 50% 50% no-repeat;
    background-size: cover;
}

However, if the height/width ratio of the box is lower than the image, you can use the old answer including max-width: 100%; for the image: Online Demo.

And if the height/width ratio of the box is higher than the image, you need to use max-height: 100% for the image: Online Demo.

For dynamic calculation, you'll need to use JavaScript. Here is a similar topic on SO.

OTHER TIPS

Try this out: http://jsfiddle.net/6rwUC/4/ I've simply added max-width: 100%;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top