tags:

views:

52

answers:

5

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.

+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
Background can't overflow.
CannibalSmith
@Cannibal: apparently you're doing it wrong.
BalusC
No, you. http://jsfiddle.net/GuzDU/1/
CannibalSmith
@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
+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
+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
+3  A: 
jessegavin
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
+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
+1 good answer I hadn't thought of centering the already wrapped image.
qw3n