hyperknot
hyperknot

Reputation: 13966

How to center and size an image to be 100% width of the screen, but only if <1024 px

OK, here was my original question, where I've left out the most important thing: to horizontally center the image, if the screen is bigger than max-width.

So far the classic trick for margin: auto doesn't work, because then width: 100% isn't the screen anymore.

#main {
margin: 0 auto;
width: 1024px;
background-color: red;
}

#bigimage {
max-width: 1024px;
width: 100%;
}   


<div id="main" role="main">
    <img src="img/bigimage.jpg" id="bigimage">
</div>

So I'm looking for an other solution. Any idea how to make max-width and horizontal centering work together?

Update:

OK, I'm almost there:

#main {
width: 100%;
text-align: center;
}

#bigimage {
max-width: 1024px;
width: 100%;
}

And it works great in all browsers, except IE8. Even IE 7 is OK! IE8 resizes the image without keeping the aspect ratio! I mean it makes it max-width wide but original width high. Can you help me how to make it not distort in IE8?

Also, a live site, with 500px max-width: http://ilhaamproject.com/

Upvotes: 1

Views: 5717

Answers (4)

Mohsen
Mohsen

Reputation: 65785

if your image have an static aspect ratio then it can be done with max-height. If you add max-height to your image based on the 1024px width (726px for 4by3 aspect ratio) then it would be fine in every browser. See the fiddle before applying max-height and after that. I just used 400px width instead.

HTML:

    <div id="container">
        <img id="bigDude" src="http://www.ladygagapic.info/wallpaper/flower-17.jpg" />
    </div>

CSS:

#container{text-align:center; border:1px solid gray;}
#bigDude{max-width:400px; width:100%;}

BUT if your images are not in same size or aspect ratio you maybe need some JavaScript just like how Facebook forced to do that.

Upvotes: 0

izolate
izolate

Reputation: 1600

Change your (updated) CSS to the following and it should work:

#main {
    width: 100%;
    text-align: center;
}

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78520

Demo

I ended up opting for display:table-row ... oh well :P

Upvotes: 0

James
James

Reputation: 218

You have the #bigimage img within the #main div. Since the main div is 1024px wide, the 100% will always be 1024. The result here is that you'll always see 1024px. If you remove the width attribute from #main or change it to 100%, you should start to see what you're looking for.

Upvotes: 0

Related Questions