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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With