それらを水平方向に中央に配置する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'});
}
});
...デモが付属しています。
誰かがより短い解決策を持っているなら、私はそれを学びたいです:)