2017-02-16 29 views
1

左に浮動小数点は、スペースが疎である場合、要素を次の行にプッシュします。新しく押された要素を、左に座るのではなく中心に置くように、残っている空間にどのように配置しますか?中央要素が浮動小数点浮動小数点:左

このコードは、たとえばhttp://codepen.io/anon/pen/QdPVweとなります。緑色のセクションは次の行にプッシュされますが、左揃えになります。一度それが押し込まれると、現在のウィンドウの幅にどのように配置しますか?あなたはボックスをフロートする必要がありますが、あなたは親に子供たちにdisplay:inline-block;text-align:center;を適用することができればわからない

<div> 
<section></section> 
<section></section> 
<section></section> 
</div> 

section { 
    width: 33%; 
    height:300px; 
    background-color:red; 
    float: left; 
    margin-right: 1%; 

} 

section:last-child { 
    background-color:green; 
    margin-right: 0%; 
} 
div{ 
    width:78%; 
    margin:0 auto; 
} 

答えて

1

あなたは別の戦略を再考することをお勧めします。 Flexは最初は怖いですが、非常に便利で強力です。

ラッパーでは、display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center;を実行できます。これは非常に良い出てくる。ここで

はcodepen例です:フレキシボックスを学習するときにここで http://codepen.io/sequential/pen/LxvJrr

は素晴らしい記事です。 https://css-tricks.com/snippets/css/a-guide-to-flexbox/

+0

クールなトリック。そして、フレックスは何らかの理由で私にとって恐ろしいです。 – sanjihan

+0

@sanjihanフレックスプロパティ名は直感的ではないので、あまりにも私のために...地獄はフレックスですが、間違いなく便利です。 – Sequential

1

section { 
 
    width: 300.33px; 
 
    height:300px; 
 
    background-color:red; 
 
    display:inline-block; 
 
} 
 

 
section:last-child { 
 
    background-color:green; 
 
    margin-right: 0%; 
 
} 
 
div{ 
 
    width:78%; 
 
    margin:0 auto; 
 
    text-align:center; 
 
}
<div> 
 
<section></section><section></section><section></section> 
 
</div>

1

よりもむしろfloat:left;使用display:inline-block;を使用して、親のdivにtext-align:center;を追加します。このため

section { 
 
    width: 300.33px; 
 
    height:300px; 
 
    background-color:red; 
 
    display:inline-block; 
 
    margin-right: 1%; 
 
} 
 

 
section:last-child { 
 
    background-color:green; 
 
    margin-right: 0%; 
 
} 
 
div{ 
 
    width:78%; 
 
    margin:0 auto; 
 
    text-align:center; 
 
}
<div> 
 
<section></section> 
 
<section></section> 
 
<section></section> 
 
</div>

1

これはフレックスボックスを使用したソリューションです。あなたが中心にしたい要素の親にflex-growを残して利用可能なスペースを残してから、justify-content: center;を使用してそのスペースに配置します。

.outer { 
 
    width: 78%; 
 
    margin: auto; 
 
} 
 
section { 
 
    width: 300.33px; 
 
    height:300px; 
 
    background-color:red; 
 
    margin-right: 1%; 
 
} 
 
.center section { 
 
    background-color:green; 
 
    margin-right: 0%; 
 
} 
 
.flex { 
 
    display: flex; 
 
} 
 
.center { 
 
    flex-grow: 1; 
 
    justify-content: center; 
 
}
<div class="flex outer"> 
 
    <div class="flex"> 
 
    <section></section> 
 
    <section></section> 
 
    </div> 
 
    <div class="flex center"> 
 
    <section></section> 
 
    </div> 
 
</div>

関連する問題