CSS网格-象棋顺序

问题描述 投票:0回答:1

我想用这样的CSS网格为PC创建自适应页面:

IMG  | Text
Text | IMG
IMG  | Text

并且对于手机来说就是这样:

IMG
Text
IMG
Text
IMG
Text

问题是我无法将每对Text IMG包装到div。如何在没有国际象棋棋盘的情况下进行这种布局?在这种情况下,使用网格模板区域将所有行移至第一行并进行合并。

img {
      max-width: 100%;
   }
   .grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-template-areas: "text img";
   }
   
   .info {
      grid-area: text;
   }
   
   .img {
      grid-area: img;
    }

   @media screen (max-width: 540px) {
      .grid {
         grid-template-columns: 1fr;
      }
   }
<div class="grid">
   <div class="info">
      <h2>Lorem, ipsum.</h2>
      <p>Lorem ipsum dolor sit amet.</p>
      <button>Lorem.</button>
   </div>
   <div class="img">
      <img src="https://via.placeholder.com/350x150" alt="">
   </div>

   <div class="info">
      <h2>Lorem, ipsum.</h2>
      <p>Lorem ipsum dolor sit amet.</p>
      <button>Lorem.</button>
   </div>
   <div class="img">
      <img src="https://via.placeholder.com/350x150" alt="">
   </div>

   <div class="info">
      <h2>Lorem, ipsum.</h2>
      <p>Lorem ipsum dolor sit amet.</p>
      <button>Lorem.</button>
   </div>
   <div class="img">
      <img src="https://via.placeholder.com/350x150" alt="">
   </div>
</div>
css css-grid
1个回答
1
投票

您可以使用grid-column调整位置:

img {
  max-width: 100%;
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow:dense; /* Don't forget this to fill all the tracks */
}
/* you pattern repeat each 4 elements */
.img:nth-child(4n + 4) { 
  grid-column:1;
}
.info:nth-child(4n + 3) {
  grid-column:2;
}
/**/

@media screen and (max-width: 540px) {
  .grid {
    grid-template-columns: 1fr;
  }
  .info:nth-child(4n + 3) {
    grid-column:1;
  }
}
<div class="grid">
  <div class="info">
    <h2>Lorem, ipsum.</h2>
    <p>Lorem ipsum dolor sit amet.</p>
    <button>Lorem.</button>
  </div>
  <div class="img">
    <img src="https://via.placeholder.com/350x150" alt="">
  </div>

  <div class="info">
    <h2>Lorem, ipsum.</h2>
    <p>Lorem ipsum dolor sit amet.</p>
    <button>Lorem.</button>
  </div>
  <div class="img">
    <img src="https://via.placeholder.com/350x150" alt="">
  </div>

  <div class="info">
    <h2>Lorem, ipsum.</h2>
    <p>Lorem ipsum dolor sit amet.</p>
    <button>Lorem.</button>
  </div>
  <div class="img">
    <img src="https://via.placeholder.com/350x150" alt="">
  </div>
  <div class="info">
    <h2>Lorem, ipsum.</h2>
    <p>Lorem ipsum dolor sit amet.</p>
    <button>Lorem.</button>
  </div>
  <div class="img">
    <img src="https://via.placeholder.com/350x150" alt="">
  </div>
  <div class="info">
    <h2>Lorem, ipsum.</h2>
    <p>Lorem ipsum dolor sit amet.</p>
    <button>Lorem.</button>
  </div>
  <div class="img">
    <img src="https://via.placeholder.com/350x150" alt="">
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.