CSSこの1行で簡単レスポンシブレイアウト!

記事
IT・テクノロジー
auto-fit(auto-fill)とminmaxを使ってレイアウトすれば、簡単にレスポンシブなレイアウトに!
今回もコピペで使えるコード付き!一緒にやって行きましょう🎵



完成見本

https:// tsuyu0102.github.io/css-sample/grid-auto-fit/index.html
▼1500px幅
1149.gif


▼768px幅
1150.gif



▼320px幅
320.gif


▼ホバーはこのようにしてみました
1155.gif



html


<section class="item-section">
   <h2>NEW ITEMS</h2>
   <div>
    <a href="#"><img src="img/item01.jpg" alt="" />Letter graphic Mens T-shirt<span class="price">&yen;6,500</span></a>
    <a href="#"><img src="img/item02.jpg" alt="" />Letter graphic Mens T-shirt<span class="price">&yen;6,500</span></a>
    <a href="#"><img src="img/item03.jpg" alt="" />Letter graphic Mens T-shirt<span class="price">&yen;6,500</span></a>
    <a href="#"><img src="img/item04.jpg" alt="" />Letter graphic Mens T-shirt<span class="price">&yen;6,500</span></a>
    <a href="#"><img src="img/item05.jpg" alt="" />Letter graphic Mens T-shirt<span class="price">&yen;6,500</span></a>
   </div>
  </section>

⭐️aタグ内に画像のimgタグや文字を入れることで、画像をクリックしても、文字をクリックしてもリンク先に飛べる👍



CSS



<style>
   body {
    background-color: rgb(24, 5, 42);
   }
   .item-section h2 {
    color: #fff;
    text-align: center;
    letter-spacing: 0.75rem;
   }
   .item-section > div {
    max-width: 1000px;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    justify-content: center;
    gap: 2rem;
    margin: 0 auto;
   }
   .item-section > div a {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    text-align: center;
    text-decoration: none;
    color: #fff;
    font-size: 1.2rem;
    padding: 1rem;
    background: rgb(24, 5, 42);
    border: solid 1px blueviolet;
    transition: 0.2s ease-in-out;
   }
   .item-section > div a:hover {
    background: rgba(255, 255, 255, 0.5);
    color: rgb(24, 5, 42);
    box-shadow: 0 0 20px rgba(255, 255, 255, 0.5);
    border-color: transparent;
   }
   .item-section > div a .price {
    display: block;
    color: #ff2d98;
    margin-top: -0.5rem;
   }
  </style>

⭐️ grid-template-columns … 横並び
⭐️auto-fit … 足りないスペースは埋める
⭐️minmax(300px, 1fr); … 最低300pxサイズを保つ



いかがでしたか?メディアクエリを書かずしてたった1行でレスポンシブなレイアウトになるのは超絶便利ですよね🌷
今回は以上です。お疲れ様でした⭐️


【参考サイト】
これは便利!CSS Gridのauto-fillとauto-fitの使い分けでRWDが捗る
https:// ascii.jp/elem/000/001/659/1659899/

サービス数40万件のスキルマーケット、あなたにぴったりのサービスを探す