Normally, you center images with 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.
views:
52answers:
5
+1
A:
Your best bet is to set it as background image of the container instead.
#container {
background: url('url/to/image.gif') no-repeat center top;
}
BalusC
2010-07-21 15:02:16
Background can't overflow.
CannibalSmith
2010-07-21 15:12:43
@Cannibal: apparently you're doing it wrong.
BalusC
2010-07-21 15:16:31
No, you. http://jsfiddle.net/GuzDU/1/
CannibalSmith
2010-07-21 15:44:07
@Cannibal: ah, I now understand what you meant with your "can't overflow". It certainly does, you just want the overflow to be **visible**. No, that's indeed not possible with only CSS background image. It's only useful when you want to have it on a `<body>`.
BalusC
2010-07-21 15:51:14
+1
A:
I don't think there is a pure CSS solution (Except for the next answer :)). However with Javascript it would be just a matter of finding the width of the image, subtracting the container width, dividing by two and you have how far to the left of the container you need.
qw3n
2010-07-21 15:03:47
+1
A:
I can only think of a Javascript solution since what you need to do is relatively position the image a negative amount to the left of its container:
jQuery
$(document).ready(function(){
var theImg = $('#container img');
var theContainer = $('#container');
if(theImg.width() > theContainer.width()){
theImg.css({
position: 'relative',
left: (theContainer.width() - theImg.width()) / 2
})
}
})
Pat
2010-07-21 15:06:21
I'd go for this solution. Note that the width of the image is unknown as per the OP's functional requirement, so you'd like to remove `width="200"` from the snippet.
BalusC
2010-07-21 16:18:58
+1
A:
A pure css solution requiring one extra wrapper (tested in FireFox, IE8, IE7):
Html:
<div class="outer"><div class="inner"><img src="/yourimage.png"/></div></div>
Css:
div.inner img {border: 1px solid blue; position: relative; left:-50%; }
div.outer {width: 300px; margin: 0 auto; border: 1px solid red; overflow: visible;}
div.inner {display: inline-block; position:relative; right: -50%;float: left;}
Borders are for illlustration purposes.
Scott
2010-07-21 17:29:28