要将它们水平居中,请添加text-align:center;
到父级:
.buttons {
position:relative;
width:100%;
margin:50px 0 0 0;
padding:0;
text-align:center;
}
演示
四周边距相等
可能有数百种更好的方法可以做到这一点,但是......这是我在星期六慵懒的下午:)
演示(调整窗口大小)
(与上面相同的html和css)
var hosts = $('.host');
var buttons= $('.buttons');
$(window).on('load resize',function(){
var w = buttons.width();
/* how many .host in one row ? */
var oneRow = Math.floor(w/300);
/* let's go! */
if(oneRow>1){
/* send hosts to the margin calculation function */
calcMargins(hosts,w,oneRow);
/* do we have some orphans?! */
var orphans = hosts.length%oneRow;
if(orphans!=0){
/* let's do the same for them */
var orphansEl = hosts.slice(-orphans);
calcMargins(orphansEl,w,orphans);
}
}else{
/* there's only one div per row, so
we reset everything */
hosts.css({'margin-left':'auto','margin-right':'auto','float':'none'});
}
});
/* here's the function */
function calcMargins(els,l,r){
/* total blank space */
var tSpace = l - (r*300);
/* we'll add a right margin for each .host and
a margin-left for the first of each row */
var nElements = r + 1;
/* it's better to leave some pixels behind
than cause a line wrap, so we'll floor the division */
var rightMargin = Math.floor(tSpace/nElements);
/* finally, we set the margins */
els.each(function(i){
if(i%r == 0){
/* left margin for first .host of each row */
leftMargin = rightMargin;
}else{
/* left margin for the rest */
leftMargin = 0;
}
/* here we go */
$(this).css({'float':'left','margin-left':leftMargin,'margin-right':rightMargin});
});
}
显然,为了清楚起见,它是这样写的,但您可以将其简化为:
var hosts = $('.host'), buttons= $('.buttons');
$(window).on('load resize',function(){
var w = buttons.width(), oneRow = Math.floor(w/300);
if(oneRow>1){
calcMargins(hosts,w,oneRow);
var orphans = hosts.length%oneRow;
if(orphans!=0) calcMargins(hosts.slice(-orphans),w,orphans);
}else{
hosts.css({'margin-left':'auto','margin-right':'auto','float':'none'});
}
});
function calcMargins(els,l,r){
var rightMargin = Math.floor((l-(r*300))/(r+1));
els.each(function(i){
leftMargin = (i%r == 0) ? rightMargin : 0;
$(this).css({'float':'left','margin-left':leftMargin,'margin-right':rightMargin});
});
}
如果你不希望“孤儿”居中,这里有一个更小的版本:
var hosts = $('.host'), buttons= $('.buttons');
$(window).on('load resize',function(){
var l = buttons.width(), r = Math.floor(l/300);
if(r>1){
var rightMargin = Math.floor((l-(r*300))/(r+1));
hosts.each(function(i){
leftMargin = (i%r == 0) ? rightMargin : 0;
$(this).css({'float':'left','margin-left':leftMargin,'margin-right':rightMargin});
});
}else{
hosts.css({'margin-left':'auto','margin-right':'auto','float':'none'});
}
});
...附带一个演示。
如果有人有更短的解决方案,我很想学习它:)