首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何创建一个响应式css网格(display: grid),使其顶行有三个相等的方框,而其余行则是两个大小相等的方框?

要创建一个响应式的CSS网格,可以使用CSS的grid-template-areas属性和grid-template-columns属性来实现。以下是一个示例的代码:

代码语言:txt
复制
<!DOCTYPE html>
<html>
<head>
  <style>
    .grid-container {
      display: grid;
      grid-template-areas:
        "box1 box2 box3"
        "box4 box5 box6"
        "box7 box8 box9";
      grid-template-columns: repeat(3, 1fr);
      grid-gap: 10px;
    }

    .box {
      background-color: #ccc;
      padding: 20px;
      text-align: center;
    }

    .box1 { grid-area: box1; }
    .box2 { grid-area: box2; }
    .box3 { grid-area: box3; }
    .box4 { grid-area: box4; }
    .box5 { grid-area: box5; }
    .box6 { grid-area: box6; }
    .box7 { grid-area: box7; }
    .box8 { grid-area: box8; }
    .box9 { grid-area: box9; }

    @media (max-width: 600px) {
      .grid-container {
        grid-template-areas:
          "box1 box2"
          "box3 box4"
          "box5 box6"
          "box7 box8"
          "box9 box9";
        grid-template-columns: repeat(2, 1fr);
      }
    }
  </style>
</head>
<body>
  <div class="grid-container">
    <div class="box box1">Box 1</div>
    <div class="box box2">Box 2</div>
    <div class="box box3">Box 3</div>
    <div class="box box4">Box 4</div>
    <div class="box box5">Box 5</div>
    <div class="box box6">Box 6</div>
    <div class="box box7">Box 7</div>
    <div class="box box8">Box 8</div>
    <div class="box box9">Box 9</div>
  </div>
</body>
</html>

在上述代码中,我们使用了grid-template-areas属性来定义网格的布局,每个方框都被分配到一个特定的区域。然后,使用grid-template-columns属性来定义每列的大小,repeat(3, 1fr)表示每列都具有相同的大小。

在媒体查询中,我们通过@media规则来定义在小屏幕设备上的布局。在这种情况下,我们将网格改为两列,每列都具有相同的大小。

这样,无论是在大屏幕还是小屏幕设备上,都可以创建一个响应式的CSS网格,顶行有三个相等的方框,而其余行则是两个大小相等的方框。

腾讯云相关产品和产品介绍链接地址:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券