Quantcast
Channel: レンタルサーバーのCPIスタッフブログ
Viewing all articles
Browse latest Browse all 131

Flexboxで、要素の左右中央寄せ、均等割り、右寄せ(justyify-content)の方法

$
0
0

Flexboxを使い、要素の左右中央寄せ、均等割り、右寄せの方法をご紹介します。

※ このドキュメントは2016年5月26日に勧告候補になったドキュメント「CSS Flexible Box Layout Module Level 1 W3C Candidate Recommendation, 26 May 2016」を参照しています。

 

方法

 

flex-containerに「justyify-content」プロパティを使用します。
各プロパティの値は下記の通りで、例えば中央寄せにしたい場合は、centerを指定します。

 

サンプルコード

 

<!DOCTYPE html>
<html lang="ja">
<head>
    <title>Flexboxテスト</title>
    <meta charset="UTF-8">
</head>

<style>
    .container{
        display: flex;
        width: 100%;
        background-color: #aaa;

        /*並び順*/
        /*
        flex-start:左寄せ(デフォルト)
        flex-end:右寄せ
        center: 中央寄せ
        space-between:残り余白の均等割り 
        space-around:左右余白 + 均等割り
        */
        justify-content: space-around;
    }
    .flex-item{
        width: 100px;
        height: 100px;
    }
    .item1{
        background-color: yellow;
    }
    .item2{
        background-color: blue;
    }
    .item3{
        background-color: green;
    }
</style>

<body>
<div class="container">
    <div class="flex-item item1">a</div>
    <div class="flex-item item2">b</div>
    <div class="flex-item item3">c</div>
</div>

</body>
</html>

実行結果

 

 

上下左右中央寄せ

 

今回は左右のポジションを変更するためのプロパティ「justyify-content」紹介でした。
上下左右中を央寄せにする場合は「align-items」と「justyify-content」を組み合わせることで可能です。

.flex-container{
  justify-content: center;
  align-items: center;
}

 

関連記事

関連タグ: 

Viewing all articles
Browse latest Browse all 131

Trending Articles