首页 > 解决方案 > 在没有媒体查询的情况下更改网格模板区域?

问题描述

我正在尝试在不使用媒体查询的情况下实现以下布局。我不喜欢使用媒体查询的原因是该内容嵌入在一个站点上,左侧有一个可以展开和折叠的侧边栏。展开的时候大概占400px,折叠的时候大概占50px。它根据用户交互而不是屏幕宽度进行扩展和折叠,因此我没有很好的方法来检测它是否从 CSS 中打开。因此,如果我使用基于屏幕宽度而不是内容的实际宽度的媒体查询,我的布局中可能会出现一些错误。有什么方法可以使用类似的东西flex-basisminmax在没有媒体查询的情况下实现这种布局?

/* functional code */

.a1 {
  grid-area: a1;
}
.a2 {
  grid-area: a2;
}
.b1 {
  grid-area: b1;
}

.grid {
  display: grid;
  grid-template-rows: 400px 200px 200px;
  grid-template-columns: 1fr 300px;
  
  grid-template-areas: 
    "a1 b1"
    "a2 b1"
    "a2 .";
}

/* Can I emulate this on the container width instead of the screen width? */
@media (max-width:1000px) {
  .grid {
    grid-template-columns: 1fr;
    grid-template-areas: "a1"
      "b1"
      "a2";
    grid-template-rows: 400px 600px 200px;
  }
  .b1 {
    width:300px;
    justify-self:center;
  }
}

/* other styling */
.grid {
  gap:8px;
}

.grid * {
  border-radius: 5px;
  background-color: lightgray;
  display: grid;
  place-items: center;
  text-align: center;
}

.collapsed { display: none; }
@media (max-width:1000px) {
  .uncollapsed {
    display: none;
  }
  .collapsed {
    display: block;
  }
}
   
<div class="uncollapsed">Uncollapsed State (make screen smaller to see collapsed state)</div>
<div class="collapsed">Collapsed State (make screen bigger to see uncollapsed state)</div>
<div class="grid">
<div class="a1">
  A1
  <br>
  Top-left normally
  <br>
  Top when collapsed
</div>
<div class="a2">
  A2
  <br>
  Bottom-left normally
  <br>
  Bottom when collapsed
</div>
<div class="b1">
  B1
  <br>
  Right side normally
  <br>
  Middle row when collapsed
</div>
</div>

仅供参考:我最终只使用了一个ResizeObserverpolyfill 和一些 JavaScript。绝对不理想,但似乎没有 JS 容器查询目前是不可能的。

标签: csscss-grid

解决方案


推荐阅读