使用纯CSS创建CSS网格布局

时间:2020-02-06 04:19:01

标签: css css-grid

我试图使用CSS Grid来创建布局,例如图像(任何项目都是正方形的):

CSS grid layout pattern

我正在尝试的代码:

CSS

  .grid-container {
    padding: 20px;
    display: grid;
    grid-gap: 20px;
    grid-auto-rows: 1fr;
    grid-template-columns: repeat(2, 1fr);
  }

  .item {
    position: relative;
    background: #ccc;
  }

  /* Square */
  .item:after {
    content: '';
    display: block;
    padding-top: 100%;
  }

  @media screen and (min-width: 640px) and (max-width: 1023px) {
    /* 640 ~ 1023 */
    .grid-container {
      grid-template-columns: repeat(3, 1fr);
    }

    .item:nth-child(6n + 1) {
      grid-column: span 2 / 3;
      grid-row: span 2;
    }
    .item:nth-child(6n + 6) {
      grid-column: span 2 / 3;
      grid-row: span 2;
      grid-column: 2 / 4;
    }
    .item:nth-child(6n + 5) {
      grid-column: span 1 / 2;
    }
  }

  @media print, screen and (min-width: 1024px) {
    /* 1024+ */
    .grid-container {
      grid-template-columns: repeat(4, 1fr);
    }

    .item:nth-child(10n + 1) {
      grid-column: span 2 / 3;
      grid-row: span 2;
    }
    .item:nth-child(10n) {
      grid-column: span 2 / 3;
      grid-row: span 2;
      grid-column-end: 5;
    }
    .item:nth-child(10n + 8) {
      grid-column-start: 1;
    }
  }

您可以在这里找到我的代码:JSFiddle

结果显示: CSS grid layout pattern

我认为将position: absolute与JavaScript一起使用来计算网格位置可以解决问题。

如何使用纯CSS创建此布局?

1 个答案:

答案 0 :(得分:5)

您可以尝试如下操作。您几乎不错,想念Module不允许项目填满所有空白。

@Module()
abstract class NavigationModule {

    @Binds
    abstract fun provideNavigator(navigator: Navigator): BaseNavigator

    @Binds
    abstract fun provideFragment1Navigation(navigator: Navigator): Fragment1Navigation 

    @Binds
    abstract fun provideFragment2Navigation(navigator: Navigator): Fragment2Navigation
}
grid-auto-flow:dense;