How to center image cropping (<img>) in a fluid-width container

How do I get an image so that it remains centered when the liquid container (based on percentages) is too small to show the whole image?

enter image description here

How to center an image inside a container

This means that it should show the middle of the image instead of the sides when the container is too small.

+46
css image responsive-design fluid-layout
Aug 15 '13 at 6:22
source share
3 answers

When he works

You may have a container that contains some content, such as two <div> , which are 50% wide each, sitting next to each other. In this example, we can illustrate only one child of the container: enter image description here

We will call the outer rectangle .container , the inner rectangle .content and the image img . This layout is beautiful, as long as .content always wider than img .

When he breaks

Since we are dealing with interest and are probably working with a responsive design, this may not always be the case. If .content always thinner than img , trimming will occur:

enter image description here

Problem

If the most interesting part of img is in the center, we need to make the browser crop both edges evenly - leaving most of it visible, regardless of the width of the .content .

enter image description here

Decision

Fortunately, a solution is possible. Moreover, additional markup is not required.

 .content { width: 90%; /* or whatever is required */ text-align: center; /* ensures the image is always in the h-middle */ overflow: hidden; /* hide the cropped portion */ } img { position: relative; /* allows repositioning */ left: 100%; /* move the whole width of the image to the right */ margin-left: -200%; /* magic! */ } 
+91
Aug 15 '13 at 6:22
source share

For new browsers you can translate it

 figure{ width: 100%; text-align: center; overflow: hidden; } img{ position: relative; left: 50%; transform: translate(-50%,0) } 

To support IE8, you can still use the technique provided by @BryceHanscomb above.

 .no-csstransforms figure img { left: 100%; /* move the whole width of the image to the right */ margin-left: -200%; /* magic! */ } 
+13
Jul 31 '14 at 17:07
source share

If you expect the image to be displayed to be much larger than the display container by setting to the left: 100%; and margin-left: -200%; (from Bryza’s answer) may not be enough to get the center of the image. Just put a higher percentage for both. Make sure the other is half the other, though.

 left: 500%; margin-left: -1000%; 
+1
Nov 17 '17 at 7:02
source share



All Articles