从 css display: grid column 继承宽度并将其应用于 position: fixed child

Inheriting width from css display: grid column and applying it to a position: fixed child

在这个例子中,我想将包含 ABC 的 div 扩展到其容器的整个宽度。

#grid {
  display: grid;
  grid-template-columns: 50% 50%;
}

.col {
  background: #ccc;
  height: 100vh;
}

.col:nth-child(2) {
  background: #aaa;
}

.bottom {
  position: fixed;
  bottom: 0;
  background: blue;
  color: white;
  width: inherit;
}
<div id="grid">
  <div class="col">
    <span>1</span>
    <div class="bottom">ABC</div>
  </div>
  <div class="col">
    <span>2</span>
  </div>
</div>

https://jsfiddle.net/ojms0rur/

我明白了:

我想要的地方:

我将如何从父网格列继承宽度并将其应用于此固定位置元素?

它以这种方式工作,因为您是从具有 width: auto 的元素继承的。

要使其按照您的预期工作,您应该明确设置网格项的宽度(例如 50vw)。在这种情况下,您可以在 grid-template-columns 值中为父网格列宽设置 auto 以避免重复 CSS。演示:

body {
  margin: 0;
}

#grid {
  display: grid;
  grid-template-columns: auto auto;
}

.col {
  background: #ccc;
  /* setting width explicitly */
  width: 50vw;
  height: 100vh;
}

.col:nth-child(2) {
  background: #aaa;
}

.bottom {
  position: fixed;
  bottom: 0;
  background: blue;
  color: white;
  width: inherit;
}
<div id="grid">
  <div class="col">
    <span>1</span>
    <div class="bottom">ABC</div>
  </div>
  <div class="col">
    <span>2</span>
  </div>
</div>

顺便说一句,设置网格列的百分比宽度将不起作用,因为网格列的百分比是相对于网格区域的,而固定位置元素的百分比是相对于屏幕的。

因为您在 .bottom div 上使用 position: fixedposition: absolute 您可以将其父级 .col 设置为 position: relative 并且在 .bottom 上使用 width: 100%,因为它现在将相对于其父级绝对定位。

Fiddle