【问题标题】:Span background color across viewport width跨越视口宽度的背景颜色
【发布时间】:2019-04-06 05:08:05
【问题描述】:

我正在尝试使用跨越视口宽度的 CSS 网格 布局构建响应式导航栏,但内部项目应居中并与页面上的其他容器元素对齐。

我想要的结果显示在下面的代码中,但是,我不认为这是一个优雅的解决方案,因为我使用了 2 个独立的 <div> 元素堆叠在一起。

一个<div> 用于使项目居中,第二个<div> 用于覆盖整个视口宽度的background-color。


有没有更好的方法使用 CSS Grid 布局?

[编辑] 我正在寻找一种方法使该技术可在多个元素上重复使用。


请将代码 sn-p 展开到整页,以便布局正确显示

.container {
  display: grid;
  grid-template-columns: 1fr repeat(4, minmax(min-content, 150px)) 1fr;
  border: 2px solid black;
  height: 100vh;
}

.nav {
  grid-area: 1 / 2 / 1 / span 4;
  height: 50px;
  background-color: grey;
  border: 1px solid red;
  position: relative;
}

.nav-underlay {
  background-color: grey;
  grid-area: 1 / 1 / 1 / span 7;
  height: 50px;
}

.content {
  grid-area: 2 / 2 / 2 / span 4;
  height: 200px;
  background-color: grey;
  border: 1px solid red;
}
<body class="container">
  <div class="nav">this box should stay aligned with the content box</div>
  <div class="nav-underlay"></div>
  <div class="content">Content box</div>
</body>

【问题讨论】:

    标签: html css css-grid


    【解决方案1】:

    由于您要扩展的背景区域仅用于装饰目的(即,您不使用该区域来传达内容),因此您可以使用 CSS 伪元素而不是实际的 HTML 元素。

    伪元素在应用于网格容器时会变成网格项 (read more)。

    .container {
      display: grid;
      grid-template-columns: 1fr repeat(4, minmax(min-content, 150px)) 1fr;
      border: 2px solid black;
      height: 100vh;
    }
    
    .nav {
      grid-area: 1 / 2 / 2 / span 4;
      height: 50px;
      background-color: grey;
      border: 1px solid red;
      position: relative;
    }
    
    .container::before {
      grid-area: 1 / 1 / 2 / 2;
      content: "";
      background-color: grey;
      height: 50px;
    }
    
    .container::after {
      grid-area: 1 / -1 / 2 / -2;
      background-color: grey;
      height: 50px;
      content: "";
    }
    
    .content {
      grid-area: 2 / 2 / 2 / span 4;
      height: 200px;
      background-color: grey;
      border: 1px solid red;
    }
    <body class="container">
      <div class="nav">this box should stay aligned with the content box</div>
      <div class="content">Content box</div>
    </body>

    jsFiddle demo

    【讨论】:

    • 这是一个不错且干净的解决方案,它回答了我最初的问题。如果我想添加另一个元素(例如横幅),它需要以类似于导航栏的方式跨越视口宽度,我只能应用 ::after 和 ::before 伪元素一次?有没有办法让这种技术在多个元素上重复使用?
    • 嗨@Michael_B,对此有什么想法:stackoverflow.com/questions/53119276/…?
    • @Lenny86,此时会很棘手,因为伪元素被视为其容器的子元素。所以,就像你说的,这只能在网格容器中完成一次。理想情况下,您可以将伪元素应用于网格项目,并使伪元素尊重主容器的行。该功能 (display: subgrid) 正在开发中,但尚不可用。 stackoverflow.com/q/47929369/3597276
    猜你喜欢
    • 2015-12-12
    • 2012-01-22
    • 1970-01-01
    • 2021-09-26
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    相关资源
    最近更新 更多