I've been looking for a way to center a div with a set max-width. I assumed I could do so by giving the div a max-width of 90% and an auto margin, then use jQuery to find and set a fixed width, which I hoped, the auto margin would then center for me.
Something like the following.
JQuery:
$(function(){
$wrap = $('#wrap');
$wrap.width($wrap.width());
});
CSS:
#wrap {
max-width:90%;
margin:auto;
}
开发者_运维问答
HTML:
<div id="wrap">
<img src="http://icdn.pro/images/en/h/a/happy-smiley-face-icone-6672-96.png" />
<img src="http://icdn.pro/images/en/h/a/happy-smiley-face-icone-6672-96.png" />
<img src="http://icdn.pro/images/en/h/a/happy-smiley-face-icone-6672-96.png" />
<img src="http://icdn.pro/images/en/h/a/happy-smiley-face-icone-6672-96.png" />
<img src="http://icdn.pro/images/en/h/a/happy-smiley-face-icone-6672-96.png" />
</div><!-- end div id="wrap" -->
So basically, I wanna make a wrapper div that I can jam full of images, but will not exceed 90% screen width; take wrapper and center it. Is this possible? I understand my JQuery thinking is almost certainly wrong. I'm very new to it, but I assumed that Javascript is the way to go about this.
No Javascript needed, everything is fine.
http://jsfiddle.net/Kyle_Sevenoaks/RvLuE/
In case anyone else is curious, I figured out a JQuery way to do what I wanted.
I have a bunch of uniformly sized images that I want in a scale-able div which also has a 90% max-width. Here's what I came up with:
JQuery:
function divResize() {
var divWidth;
var extra;
divWidth = $(window).width() * .9;
extra = divWidth % /*IMAGE SIZE IN PX*/;
divWidth = (divWidth - extra);
$("#wrap").css({ width: divWidth });
}
$(document).ready(divResize);
$(window).resize(divResize);
CSS:
#wrap {
margin:auto;
}
HTML:
<div id="wrap">
<img src="/images.png" />
<img src="/images.png" />
<img src="/images.png" />
<img src="/images.png" />
<img src="/images.png" />
</div>
I guess my real problem was that I couldn't adequately explain my problem. Thanks for the help everybody.
What isn't working here? This works fine for me, but I don't think you need javascript?
<html>
<body>
<style>
body { }
#wrap {max-width: 90%; margin: auto; background-color: red}
</style>
<div id='wrap'>a a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa aa a a a aa a<br/>a</div>
If you want to center a possibly short row, set wrap's text-align to center, or make it display:inline-block if you have a border you need to show.
精彩评论