How do I center an image if it's wider than its container?
Normally, you center images with display: block; margin: auto
display: block; margin: auto
, but if the image is larger than the container, it overflows to the right. How do I make it overflow to the both sides equally? The width of the container is fixed and known. The width of the image is unknown.
HTML
<div class="image-container">
<img src="http://www.google.com/images/logo.gif" height="100" />
</div>
CSS
.image-container {
width: 150px;
border: solid 1px red;
margin:100px;
}
.image-container img {
border: solid 1px green;
}
jQuery
$(".image-container>img").each(function(i, img) {
$(img).css({
position: "relative",
left: ($(img).parent().width() - $(img).width()) / 2
});
});
See it on jsFiddle: http://jsfiddle.net/4eYX9/30/
A pure css solution
Requiring one extra wrapper (tested in FireFox, IE8, IE7):
Improved Answer
There was a problem with the original answer (below). If the image is larger than the container that outer
is centered on with it's auto margins, then it truncates the image on the left and creates excessive space on the right, as this fiddle shows.
We can resolve that by floating inner
right and then centering from the right. This still truncates the img
off the page to the left, but it does so by explicitly pushing it that way and then centers back off of that, the combination of which is what prevents the extra horizontal scroll on the right. Now we only get as much right scroll as we need in order to see the right part of the image.
Fiddle Example (Borders in fiddle are for demo only.)
Essential CSS
div.outer {
width: 300px; /* some width amount needed */
margin: 0 auto;
overflow: visible;
}
div.inner {
position:relative;
float: right; /* this was added and display removed */
right: 50%;
}
div.inner img {
position: relative;
right:-50%; /* this was changed from "left" in original */
}
If you desire no right scroll at all for wide images
Then using the above, also set whatever element wraps outer
(like body
or a third wrapper) to have overflow: hidden
.
Original Idea (for History)
Fiddle Example (Borders in fiddle are for demo only.)
HTML
<div class="outer">
<div class="inner">
<img src="/yourimage.png">
</div>
</div>
CSS
div.outer {
width: 300px; /* some width amount needed */
margin: 0 auto;
overflow: visible;
}
div.inner {
display: inline-block;
position:relative;
right: -50%;
}
div.inner img {
position: relative;
left:-50%;
}
这是一个2行CSS解决方案(跨浏览器支持可能需要多行):
img {
margin-left: 50%;
transform: translateX(-50%);
}
链接地址: http://www.djcxy.com/p/89232.html