Flexbox: 水平方向と垂直方向の中央揃え 質問する

Flexbox: 水平方向と垂直方向の中央揃え 質問する

flexbox を使用して、コンテナー内で div を水平方向および垂直方向に中央揃えする方法。以下の例では、各数字を (行ごとに) 上下に並べ、水平方向に中央揃えにしたいと考えています。

.flex-container {
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;
  align-items: center;
  justify-content: center;
}
row {
  width: 100%;
}
.flex-item {
  background: tomato;
  padding: 5px;
  width: 200px;
  height: 150px;
  margin: 10px;
  line-height: 150px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
}
<div class="flex-container">
  <div class="row">
    <span class="flex-item">1</span>
  </div>
  <div class="row">
    <span class="flex-item">2</span>
  </div>
  <div class="row">
    <span class="flex-item">3</span>
  </div>
  <div class="row">
    <span class="flex-item">4</span>
  </div>
</div>

http://codepen.io/anon/pen/zLxBo

ベストアンサー1

次のようなものが欲しいと思います。

html, body {
    height: 100%;
}
body {
    margin: 0;
}
.flex-container {
    height: 100%;
    padding: 0;
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}
.row {
    width: auto;
    border: 1px solid blue;
}
.flex-item {
    background-color: tomato;
    padding: 5px;
    width: 20px;
    height: 20px;
    margin: 10px;
    line-height: 20px;
    color: white;
    font-weight: bold;
    font-size: 2em;
    text-align: center;
}
<div class="flex-container">
    <div class="row"> 
        <div class="flex-item">1</div>
        <div class="flex-item">2</div>
        <div class="flex-item">3</div>
        <div class="flex-item">4</div>
    </div>
</div>

デモは以下をご覧ください:http://jsfiddle.net/audetwebdesign/tFscL/

高さと上部/下部のパディングを適切に機能させたい場合は、要素をブロック レベル ( ではなく )に.flex-itemする必要がありますdivspan

また、 では、ではなく の.row幅を設定します。auto100%

あなたの.flex-container特性は問題ありません。

.rowをビューポート内で垂直方向に中央揃えにしたい場合は、htmlおよびに 100% の高さを割り当てbody、余白も 0 にしますbody

垂直方向の配置効果を確認するには高さが必要であることに注意してください。.flex-container高さがない場合、コンテナーはコンテンツを囲むために必要な最小の高さを計算します。この例では、ビューポートの高さよりも小さくなります。

脚注:
flex-flow、プロパティflex-directionを使用すると、このデザインをより簡単に実装できます。要素の周囲にスタイル (背景画像、境界線など) を追加する場合を除き、コンテナーは必要ないflex-wrapと思います。.row

役に立つリソースは次のとおりです。http://demo.agektmr.com/flexbox/

おすすめ記事