问题
I have an image that has been placed inside a div. The div is 600 width and has a variable height.
I want my image to sit at the top of the div. If I make the width 590 the issue is that the image is then too high in terms of design and it looks too dominant on the page (because its ratio is roughly 4:3 etc).
So I want to make the image 590 by 200. If i use...
.img {
width: 590px;
max-height: 200px;
}
...then the image sits inside the div exactly how I want it. However, the photo itself is squashed and distorted into the 590 by 200. How can I ensure that the image just crops within that size and has no distortion?
I have no access to the html so cant add a wrapper around it either unfortunately... This will need to be done only by editing the CSS class .img.
EDIT - Andy is right, negative margins are the only way I can get this to work. Thank you Andy.
回答1:
You cannot do that simply by editing the css. You need to put the image as background-image in HTML
<div class="cover">
<div style="background-image: url(http://img.youtube.com/vi/6WNyczNYsc0/0.jpg); " class="video-thumbnail"></div>
</div>
and using background-size: cover;
in css
CSS
.cover {
width: 590px;
height: 200px;
}
.video-thumbnail {
height: 100%;
background-size: cover;
-moz-background-size: cover;
-webkit-background-size: cover;
background-position: center;
}
DEMO HERE
In the demo I placed the background-position as center.
回答2:
You can put this image into div background-image style, and then use CSS3 style - background-size: cover
回答3:
try this:
.img {
width: auto;
max-height: 200px;
}
warning: auto width doesn't work in IE7 (and I'm not sure about IE8). You may have to use js solutions for backward compatibility.
来源:https://stackoverflow.com/questions/13582051/using-just-css-crop-img-keeping-aspect-without-distortion