LoginSignup
1
2

More than 3 years have passed since last update.

Flex: PCで左←右、スマホで上→下の並び

Last updated at Posted at 2020-05-15

お題:広い画面でボタンを右から左に並べ、狭い画面で上から下に並べる。

flex-direction.png

答え:flex-direction: row-reverse を使う。

参考: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container#Alignment_and_flex-direction

HTMLはこんな感じです。Bootstrapを使っています。

    <div class="card shadow m-4">
      <div class="card-body">
        <div class="row row-submit">
          <div class="col-sm text-right">
            <button type="button" class="btn btn-primary">送信</button>
          </div>
          <div class="col-sm">
            <button type="button" class="btn btn-danger">キャンセル</button>
          </div>
        </div>
      </div>
    </div>

CSSはこんな感じです。デフォルトはモバイル版とし、広い画面で(@media (min-width: 576px))デザインを変えています。

  .row-submit button {
    width: 100%;
  }
  .row-submit .col-sm:not(:last-child) {
    margin-bottom: 1.5rem;
  }
  @media (min-width: 576px) {
    .row-submit {
      flex-direction: row-reverse;
      justify-content: flex-end;
    }
    .row-submit button {
      width: auto;
    }
    .row-submit button.btn-primary {
      width: 70%;
    }
    .row-submit .col-sm:not(:last-child) {
      margin-bottom: 0;
    }
  }

Bootstrapでは、.row と .col-sm には次のようなCSSが設定されています。

  .row {
    display: flex;
    flex-wrap: wrap;
  }
  @media (min-width: 576px) {
    .col-sm {
      flex-basis: 0;
      flex-grow: 1;
    }
  }
1
2
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
1
2