Centering floating list items <li> inside a div or their <ul>

半城伤御伤魂 提交于 2019-12-02 22:52:02

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.

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));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!