跨视口宽度的跨度背景颜色 [英] Span background color across viewport width

查看:102
本文介绍了跨视口宽度的跨度背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to build a responsive navigation bar with CSS Grid layout that spans across the viewport width, but the inner items should be centred and aligned with other container elements on the page.

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

The result that I want is displayed in the code below, however, I don't feel that this is an elegant solution as I used 2 separate <div> elements stacked on top of each other.

一个÷ 用于使项目居中,第二个< div> 将覆盖整个视口宽度的背景颜色

One <div> is for having the items centred and the second <div> is to cover the background-color across the viewport width.

是否有更好的方法使用 CSS网格布局?

Is there a better way of doing this using the CSS Grid layout?

我正在寻找一种使该技术可在多个元素上重用的方法。

请将代码段扩展到整页,以便正确显示布局

Please expand the code snippet to full page so the layout appears correctly

.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>

推荐答案

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

Since the background area you're looking to expand is for decorative purposes only (i.e., you're not using that area to convey content), then you can use CSS pseudo-elements instead of an actual HTML element.

伪元素在应用于网格容器时会变成网格项(了解详情)。

Pseudo-elements become grid items when applied to a grid container (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>

这篇关于跨视口宽度的跨度背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆