Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an image of 400px and a div that is smaller (the width is not always 300px as in my example). I want to center the image in the div, and if there is an overflow, hide it.

Note: I must keep the position:absolute on the image. I'm working with css-transitions, and if I use position:relative, my image shakes a bit (https://web.archive.org/web/20120528225923/http://ta6.maxplus.be:8888/).

jsfiddle http://jsfiddle.net/wjw83/1/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
397 views
Welcome To Ask or Share your Answers For Others

1 Answer

You should make the container relative and give it a height as well and you're done.

http://jsfiddle.net/jaap/wjw83/4/

.main {
  width: 300px;
  margin: 0 auto;
  overflow: hidden;
  position: relative;
  height: 200px;
}

img.absolute {
  left: 50%;
  margin-left: -200px;
  position: absolute;
}
<div class="main">
  <img class="absolute" src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />
</div>
<br />
<img src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...