Reputation: 20115
Currently, all my images look like this:
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:
In this case, I would like to only reveal the topmost square of the image:
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.
Upvotes: 16
Views: 28912
Reputation: 72261
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;
}
Upvotes: 9
Reputation: 26380
Actually, you can do this with a single tag - one div. Does it matter that it's not one img tag?
<div style="display: inline-block; width: 50px; height: 50px; background: url(test.jpg);"></div>
You never use an <img>
tag, you just set up the div and you're done. Set the size, add padding, border, etc, and preferable put all the reusable styles into a class and set the background image on a per div basis. You end up with this:
<div class="hip2bsquare" style="background: url(test.jpg);"></div>
CSS:
.hip2bsquare {
display: inline-block;
width: 50px;
height: 50px;
border: 3px solid #FFF;
outline: 1px solid #000;
}
This uses the border to add white and outline to add black. It's probably an abuse of the box model, but it should give you the visual.
Upvotes: 1
Reputation: 45
I think you're looking for the CLIP property within CSS:
.photo-clipped {
position: absolute;
clip: rect(0px,64px,64px,0px);
}
<img src="some_image.gif" class="photo photo-clipped" />
Upvotes: 0
Reputation: 6406
Take a look at the clip
property.
http://www.w3schools.com/cssref/pr_pos_clip.asp
Here an example with your image: http://jsfiddle.net/2U3CE/1/
Code:
img{
position:absolute;
clip:rect(0,73px,73px,0);
}
Upvotes: 8