问题
I have a div that contains an image element set up as such:
<div id="container">
<img src="cat.jpg"/>
</div>
And CSS:
#container {
width: 150px;
height: 200px;
}
#container img {
width: 200px;
height: 200px;
overflow: none;
}
Currently the container width is smaller then the img width meaning that right part of the image is cropped out which is what I want. However, I would like the left part of the image to be cut out instead.
I've tried experimenting with background positioning but haven't gotten what I wanted. Does anyone know of the correct way to achieve this?
To clarify, I would like to achieve the effect represented in the blue box below (where the faded out section isn't actually visible of course):

回答1:
This should work:
#container {
width: 150px;
height: 200px;
overflow: hidden;
}
#container img {
width: 200px;
height: 200px;
margin-left: -50px;
}
回答2:
Here's a fairly simple solution...
HTML
<div class="cat"></div>
CSS
.cat {
position: absolute;
background-image: url('http://www.deargrumpycat.com/wp-content/uploads/2013/02/Grumpy-Cat1.jpg');
background-position: right center;
background-size: 200px 200px; // set bg size
height: 200px; // no need for container
width: 150px;
}
DEMO
回答3:
You can accomplish this by floating the image.
http://jsfiddle.net/9AmVA/2/
#container {
/* Making crop dimensions bigger so I can see the edge of the cat to know it's working correctly */
width: 600px;
height: 500px;
overflow: hidden;
}
#container:after { clear: right;
display: block;
height: 0;
visibility: hidden;
content: ' '; }
#container img {
float: right;
}
回答4:
.container {
max-width: 150px;
min-width: 150px;
height: 200px
display: inline-block;
background-image: url("PATH-TO/YOUR-IMAGE.JPG");
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: 100%;
overflow:hidden;
}
.container img {
display: block;
position: relative;
width: 100%;
height: auto;
visibility: hidden;
}
By using background size and position you will have much more control over the positioning or composing the image. you can automate this using javascript as well. I would suggest not to use id's instead use className or data attribute.
来源:https://stackoverflow.com/questions/20060807/css-change-element-width-from-different-direction