Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show only a portion of an image just by using the img tag?

Tags:

css

Currently, all my images look like this:

enter image description here

HTML

<img class="photo" src="foo.png" />

CSS

.photo {
   padding: 3px;
   border: 1px solid #000;
   background: #fff;
   width: 64px;
   height: 64px;
   display: block;
}

This expects the aspect ratio of the image to always be 1:1. Now, a new project requirement has come in that the images do not have to be 1:1. Rather, they can be tall rectangles:

enter image description here

In this case, I would like to only reveal the topmost square of the image:

enter image description here

How can this be done with a single <img> tag? I know how to do it with two tags - just wrap the img with a div, apply 3px padding to the div and place the URL as the background-image of the img. But I would like to know how to do this in a cleaner way, without an additional HTML tag.

like image 574
JoJo Avatar asked Mar 08 '12 20:03

JoJo


1 Answers

Final Update--tested IE8+: This solution uses a refinement of Surreal Dreams' idea of using outline for getting the border. This allows a cross browser simplicity compared to the linear-gradient method I was previously going for. It works in IE7, except the outline (unsupported).

Keeping it as an img tag with a src keeps it semantic.

A margin: 1px is applied to give the outline "space" in the layout, since by nature outline takes up no space. The zero height suppresses the main image, and the padding is used create the desired height for the background image (which is set the same as the main image) to show.

HTML

<img class="photo" src="foo.png" style="background-image: url(foo.png)" />

CSS

.photo {
   padding: 64px 0 0 0;
   border: 3px solid #fff;
   outline: 1px solid #000;
   margin: 1px;
   width: 64px;
   height: 0px;
   display: block;
}
like image 92
ScottS Avatar answered Sep 27 '22 21:09

ScottS