Question

Within a surrounding div I want to center an image. This image should have a forced size but without stretching. So if the div container is 100px*100px and the image 200px*200px, 50px should be cropped on each side.

In this question you can read how to force the size. But I don't want the image to start on the bottom left but to center it. This is the question :)

This is how it is:

enter image description here

And this is how I want it to be:

enter image description here

Was it helpful?

Solution

Give the image a negative left margin. In this example, margin-left:-50px.

Edit: Or if you don't know the width of the image, you can use the image as a background for the div.

<div style="margin:0 auto; width:100px; height:100px; border:2px solid black;
  background:url(yourimagehere) 50% 0 no-repeat">
</div>

OTHER TIPS

This might be what you need?

This works even if the orientation of the container doesn't match the orientation of the image (portrait/landscape). The zoom(0.1) and min-width/height:1000% mean it works if the image size is up to 10x that of the target container, I guess you have to draw a line somewhere: (http://jsfiddle.net/FYnCG/). The animation bit is just a test, if you will, so you see how it scales when the height becomes the limiting factor.

<DOCTYPE html>
<html>
<head>
<style>
.container {
  width: 100px;
  height: 30px;
  border: 1px solid black;
  overflow:hidden;
  position:relative;
  transititon: width 5s, height 8s;
}
.container img {
  position: absolute;
  left:-10000%; right: -10000%; 
  top: -10000%; bottom: -10000%;
  margin: auto auto;
  min-width: 1000%;
  min-height: 1000%;
  -webkit-transform:scale(0.1);
  transform: scale(0.1);
}
.container:hover {
  width: 800px;
  height: 800px;
  transition: width 5s, height 8s;
}
</style>
</head>
<body>
  <div class="container">
    <img 
       src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" 
       />
    <!-- 366x200 -->
  </div>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top