问题
HTML:
<div class="imgcontainer">
<ul>
<li><img src="1.jpg" alt="" /></li>
<li><img src="2.jpg" alt="" /></li>
.....
</ul>
</div>
I'm coding a simple gallery page by creating unordered list and each list item of it contains an image.
ul li {
float: left;
}
I set the width of the container as "max-width" so I can make possible to fit the list items (images) to the browser width.. meaning that they will be re-arranged when the browser window re-sized.
.imgcontainer{
max-width: 750px;
}
Now the problem is those images or list items are not aligned to center, they are aligned to the left of .imgcontainer body (colored gray in the attached link below), leaving a space on the right when the window re-sized!
How can I center those images every time the window resized?
Here's the whole page/code you can preview it or edit it at JS Bin
http://jsbin.com/etiso5
回答1:
Remove float:left
and use display:inline
so that you can use text-align:center
. Set the font size to zero so that you don't have white-space between the images.
ul {
font-size:0;
text-align:center
}
ul li {
display:inline;
zoom:1
}
.imgcontainer {
max-width:750px;
margin:0 auto
}
The zoom
is a hack for old IE versions. This is however not a valid CSS property, so won't go through the W3C validator.
回答2:
This assumes that all items are the same width. If you don't want the last row of items to be centered, you can accomplish this with a few lines of JavaScript. Ditch the inline-block, text-align center stuff, and just float your list elements and put margin: 0 auto
on the list container.
On the JS side of things, calculate the width of your content pane or window, next determine how many items you can fit in a row, i.e. the list container element's width, and then set that width. itemWidth
here assumes each list item's width + margin + padding + border.
var centerListItems = function (itemWidth) {
var $paneWidth = $('#my-content').width(),
setWidth;
setWidth = parseInt(($paneWidth / itemWidth), 10) * itemWidth;
$('#my-list').width(setWidth);
}
If you want it to change when the window is resized or orientation is changed, you can use underscore.js to debounce the call.
var event;
if ('onorientationchange' in window) {
event = 'onorientationchange';
} else {
event = 'resize';
}
$(window)
.off(event)
.on(event, _.debounce(function () {
centerListItems(itemWidth);
}, 350));
来源:https://stackoverflow.com/questions/6235938/centering-floating-list-items-li-inside-a-div-or-their-ul