CSS网格-仅在桌面上元素的替代顺序

问题描述 投票:2回答: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;
   }

   @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个回答
2
投票

您可以使用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 + 2) { 
  grid-column:1;
}
.info:nth-child(4n + 1) {
  grid-column:2;
}
/**/

@media screen and (max-width: 540px) {
  .grid {
    grid-template-columns: 1fr;
  }
  .info:nth-child(4n + 1) {
    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.