LoginSignup
0
0

More than 3 years have passed since last update.

flexboxで要素の順番を入れ替える。

Posted at

flexboxでbox内で順番を入れ替える方法をご紹介いたします。レスポンシブで結構使う時があると思いますので、ぜひ覚えてください。

横並びのよくみるレイアウト

まずはHTML。

index.html
    <div class="parent">
        <div class="child child-1">1</div>
        <div class="child child-2">2</div>
        <div class="child child-3">3</div>
    </div>

次にCSSです。

style.css
.parent{
    display: flex;
}
.child{
    width: 100px;
    height: 100px;
    background: red;
    color: white;
    margin-right: 10px;
}
.child-1{
    order: 0;
}
.child-2{
    order: 1;
}
.child-3{
    order: 2;
}

これで下記のようになります。

スクリーンショット 0003-04-02 9.55.31.png

このorderのスタイルは順番を入れ替える必要のない時は必要ありません。
それでは、入れ替える方法を見ていきましょう。

flexboxで要素を入れ替える

要素を入れ替えるスタイルはこうです。

style.css
.parent{
    display: flex;
}
.child{
    width: 100px;
    height: 100px;
    background: red;
    color: white;
    margin-right: 10px;
}
.child-1{
    order: 2;
}
.child-2{
    order: 1;
}
.child-3{
    order: 0;
}

こうするとこのようになります。

スクリーンショット 0003-04-02 10.07.18.png

つまり、orderを指定するだけで順番の入れ替えが容易にできてしまいます。注意する点は、orderは0からスタートすることです。

縦並びでも入れ替える

次に縦並びでも入れ替えを見てみましょう。
HTMLは変わらず、CSSが変わります。

style.css
.parent{
    display: flex;
    flex-direction: column;
}
.child{
    width: 100px;
    height: 100px;
    background: red;
    color: white;
    margin-bottom: 10px;
}
.child-1{
    order: 0;
}
.child-2{
    order: 1;
}
.child-3{
    order: 2;
}

これでこうなります。

スクリーンショット 0003-04-02 10.20.19.png

これを入れ替えます。

style.css
.parent{
    display: flex;
    flex-direction: column;
}
.child{
    width: 100px;
    height: 100px;
    background: red;
    color: white;
    margin-bottom: 10px;
}
.child-1{
    order: 2;
}
.child-2{
    order: 1;
}
.child-3{
    order: 0;
}

こうなります。
スクリーンショット 0003-04-02 10.23.40.png

このように例え縦並びだったとしてもorderの指定で簡単に順番を入れ替えることができます。

覚えておきましょう!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0