从css display:grid列继承宽度并将其应用于某个位置:fixed child

时间:2017-08-05 16:54:41

标签: html css css3 css-position css-grid

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

<div id="grid">
  <div class="col">
    <span>1</span>
    <div class="bottom">ABC</div>
  </div>
  <div class="col">
    <span>2</span>
  </div>
</div>
 (1/1) Swift_TransportException Failed to authenticate on SMTP server
 with username "xxxx@gmail.com" using 2 possible authenticators in AuthHandler.php (line 181)

https://jsfiddle.net/ojms0rur/

我得到了这个: Problem Screen Capture

我想要的地方:

Solution Sketch

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

2 个答案:

答案 0 :(得分:2)

这是以这种方式工作的,因为你继承了width: auto的元素。

为了使它按预期工作,你应该明确地设置网格项的宽度(例如50vw)。在这种情况下,您可以在auto值中为父网格列宽设置grid-template-columns以避免重复的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>

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

答案 1 :(得分:0)

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

Fiddle