首页 > 解决方案 > 如何使 CSS 二维网格响应?

问题描述

我有一个带有网格的二维 CSS。我无法实现响应能力。当屏幕按需要填满时,我得到以下信息。

在此处输入图像描述

我压缩了第 2 列和第 3 列,而不是如下响应。

在此处输入图像描述

我想要以下结果。

在此处输入图像描述

请看下面的代码:

.frame {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  grid-template-rows: repeat(2, 1fr);
  grid-gap: 40px;
  border: 1px solid red;
}

.blog1,
.blog2,
.blog3,
.blog4 {
  height: 200px;
  border: 1px solid green;
}

.blog3 {
  grid-column: 3;
  grid-row: 1/3;
  height: 100%;
}

.blog4 {
  height: 200px;
  border: 1px solid green;
  grid-column: 1/3;
  grid-row: 2;
}
<div class="frame">
  <div class="blog1">one</div>
  <div class="blog2">two</div>
  <div class="blog3">three</div>
  <div class="blog4">four</div>
</div>

标签: htmlcssgrid

解决方案


尽管您可以将宽度更改为任何内容或将媒体更改为您想要的屏幕,但这将做到这一点!

.frame {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  grid-template-rows: repeat(2, 1fr);
  grid-gap: 40px;
  border: 1px solid red;
}

.blog1,
.blog2,
.blog3,
.blog4 {
  height: 200px;
  border: 1px solid green;
}

.blog3 {
  grid-column: 3;
  grid-row: 1/3;
  height: 100%;
}

.blog4 {
  height: 200px;
  border: 1px solid green;
  grid-column: 1/3;
  grid-row: 2;
}

@media screen and (max-width: 2000px) {
  .frame {
   grid-template-columns: auto;
   grid-template-rows: none;
   }
   .blog1, .blog2, .blog3, .blog4 {
   width: 100%;
   height: 200px;
   grid-column: auto;
   grid-row: auto;
   }
   }
  <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="">
  <title>Document</title>
</head>
<body>
  <div class="frame">
    <div class="blog1">one</div>
    <div class="blog2">two</div>
    <div class="blog3">three</div>
    <div class="blog4">four</div>
  </div>
</body>
</html>


推荐阅读