search
LoginSignup
7

More than 1 year has passed since last update.

posted at

Gridレイアウトで、全体を中央寄せしつつ、最終行を左寄せにする

flexboxを使うとうまくいかない

justify-content: centerだとこうなる。
 2021-03-17 14.38.05.png

justify-content: flex-startだとこうなる。
 2021-03-17 14.38.53.png

justify-content: flex-start+widthを指定+margin: autoだとこうなる。
 2021-03-17 14.40.45.png

解決策

display: gridを使う

html
<div class="container">
  <div class="item">item1</div>
  <div class="item">item2</div>
  <div class="item">item3</div>
  <div class="item">item4</div>
  <div class="item">item5</div>
  <div class="item">item6</div>
  <div class="item">item7</div>
</div>
css
.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, 300px);
  grid-row-gap: 20px;
  grid-column-gap: 10px;
  justify-content: center;
  width: 90%;
  margin: 0 auto;
}

.item {
  padding: 12px;
  background-color: yellow;
}

 2021-03-17 14.46.45.png
 2021-03-17 14.47.38.png

See the Pen xxRNwLo by d0ne1s (@d0ne1s) on CodePen.

参考

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
What you can do with signing up
7