首页 > 解决方案 > 使用自动调整和自动填充在 CSS Grid 中调整列大小时遇到​​问题

问题描述

我正在尝试使用 CSS 进行布局,其中我有一个 2 列和 2 行的网格。

第一列的宽度应为1fr,第二列应为4fr

我尝试使用auto-fit

HTML

<body>
  <header>
    <div class="item1">GRID ITEM 1</div>
    <div class="item2">GRID ITEM 2</div>
    <div class="item1">GRID ITEM 3</div>
    <div class="item2">GRID ITEM 4</div>
  </header>
</body>

CSS

header {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    }

    div {
      border: 1px solid;
    }

我无法设置 2 个不同的列宽,(1fr, 3fr)仅在桌面屏幕模式下使用时auto-fitauto-fill有没有办法在不使用媒体查询的情况下实现这一点?或者auto-fit并且auto-fill仅在列具有相同宽度时使用?

标签: cssresponsive-designcss-grid

解决方案


所以如果我理解正确的话。您的布局应该有 5 列(1 x 1fr、1 x 4fr)和 2 行。这可能会回答您的问题。

.parent {
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-template-rows: repeat(2, 1fr);
height: 300px;
}

.item1 { grid-area: 1 / 1 / 2 / 2; background: red;}
.item2 { grid-area: 1 / 2 / 2 / 6; background: green; }
.item3 { grid-area: 2 / 1 / 3 / 2; background: yellow; }
.item4 { grid-area: 2 / 2 / 3 / 6; background: blue; }
<div class="parent">
<div class="item1"> </div>
<div class="item2"> </div>
<div class="item3"> </div>
<div class="item4"> </div>
</div> 


推荐阅读