CSS网格:根据屏幕大小的自适应网格

时间:2019-11-27 13:28:09

标签: css flexbox css-grid

这就是我想要实现的目标:

在移动设备上

enter image description here

在平板电脑/ iPad和台式机上

enter image description here

这是我到目前为止所拥有的。

article {
    display: grid;
    height: auto;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: auto;
    justify-items: center;
    align-items:center;
}

section {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50%;
  height: 50%;
}

section img {
  max-width: 4rem;
}
<article>
  <section><img src="https://i.pinimg.com/originals/d3/87/68/d38768f93e7acebc36b42feeb77f9978.png" alt=""></section>
  <section><img src="https://www.freepnglogos.com/uploads/netflix-logo-0.png" alt=""></section>
    <section><img src="https://i.pinimg.com/originals/d3/87/68/d38768f93e7acebc36b42feeb77f9978.png" alt=""></section>
  <section><img src="https://www.freepnglogos.com/uploads/netflix-logo-0.png" alt=""></section>
    <section><img src="https://i.pinimg.com/originals/d3/87/68/d38768f93e7acebc36b42feeb77f9978.png" alt=""></section>
  <section><img src="https://www.freepnglogos.com/uploads/netflix-logo-0.png" alt=""></section>
    <section><img src="https://i.pinimg.com/originals/d3/87/68/d38768f93e7acebc36b42feeb77f9978.png" alt=""></section>
  <section><img src="https://www.freepnglogos.com/uploads/netflix-logo-0.png" alt=""></section>
    <section><img src="https://i.pinimg.com/originals/d3/87/68/d38768f93e7acebc36b42feeb77f9978.png" alt=""></section>
  <section><img src="https://www.freepnglogos.com/uploads/netflix-logo-0.png" alt=""></section>
    <section><img src="https://i.pinimg.com/originals/d3/87/68/d38768f93e7acebc36b42feeb77f9978.png" alt=""></section>
  <section><img src="https://www.freepnglogos.com/uploads/netflix-logo-0.png" alt=""></section>
      <section><img src="https://i.pinimg.com/originals/d3/87/68/d38768f93e7acebc36b42feeb77f9978.png" alt=""></section>
  <section><img src="https://www.freepnglogos.com/uploads/netflix-logo-0.png" alt=""></section>
      <section><img src="https://i.pinimg.com/originals/d3/87/68/d38768f93e7acebc36b42feeb77f9978.png" alt=""></section>
  <section><img src="https://www.freepnglogos.com/uploads/netflix-logo-0.png" alt=""></section>
      <section><img src="https://i.pinimg.com/originals/d3/87/68/d38768f93e7acebc36b42feeb77f9978.png" alt=""></section>
  <section><img src="https://www.freepnglogos.com/uploads/netflix-logo-0.png" alt=""></section>
</article>

我如何确保它在台式机和ipad上保持 5列(或者将来可能会增加或更少),并且将其固定为 3列手机屏幕

我希望在屏幕之间进行平滑过渡,因此在屏幕尺寸之间不要躲藏起来。 建议/帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

只需为小屏幕设备创建一个不同的grid-template-columns定义:

article {
    grid-template-columns: repeat(5, minmax(0, 1fr));
}

@media screen and (max-width: 480px) {
  article {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}
  

我希望在屏幕之间进行平滑过渡,因此屏幕尺寸之间不会出现躲闪的现象。

这取决于浏览器如何处理。为了保证有一个更平滑的解决方案,您将不得不诉诸基于Javascript的解决方案(这可能很复杂,而且imo,不值得)。