How do I get an image to stay centered when its fluid width (percentage based) container is too small to show the whole image?
How can I center the image inside it's container
This means it should show the middle of the image instead of the sides when container is too small.
By setting overflow:hidden to the div containing the image, and height:100% to the image, it will be resized to fill the height of the div, without distortion. Then we use jQuery to center the image with position:absolute .
You might have a container that holds some content such as two <div>
s that are 50% wide each, sitting next to each other. For this example, we can illustrate just one child of the container:
We'll name outer rectangle .container
, the inner rectangle .content
and the image img
. This arrangement is perfectly fine, as long as .content
is always wider than img
.
Since we're dealing with percentages and probably working with a responsive design, this may not always be the case. If .content
is ever thinner than img
, cropping will occur:
If the most interesting part of img
is in the center, we need to get the browser to crop both edges evenly - leaving the best part of it visible, no matter what width of .content
is.
Fortunately, a solution is possible. Even better, no extra markup is 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! */ }
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 presented above by @BryceHanscomb.
.no-csstransforms figure img { left: 100%; /* move the whole width of the image to the right */ margin-left: -200%; /* magic! */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With