是否可以在没有包装器的情况下在固定宽度的 div 上创建全宽背景?

Is it possible to create a full width background on a fixed-width div without a wrapper?

提问人:Jeff 提问时间:10/24/2021 最后编辑:Jeff 更新时间:10/24/2021 访问量:86

问:

是否可以在没有包装器的情况下使 div one 看起来像 div two?例如,扩展背景图像以填充 100% 的水平屏幕?

这是一把小提琴演示了我的问题

div.one,
div.two {
  width: 300px;
  margin: auto;
  color: #fff;
}
div.one,
div.wrapper {
  background-color: #1e1e1e;
  background-image: url("https://www.transparenttextures.com/patterns/circles.png");
  background-attachment: fixed;
}
<div class="one">
  Div one is 300px wide and centered
</div>
<div class="wrapper">
  <div class="two">
    Div two is 300px wide and centered with a 100%-width wrapper
    Is it possible to make div one look like div two without a wrapper?
  </div>
</div>

我想这可能是一个解决方案,但不确定。我也在搞砸,但我似乎无法使背景图像显示在 div 的边界之外。border-imageclip-path: inset(0 -50rem 0 -50rem)

CSS的

评论

1赞 Sharad Raj 10/24/2021
它已经是全宽的了,你能详细说明一下你的期望吗?为什么不在不固定的情况下将背景添加到 div 秒本身
0赞 Jeff 10/24/2021
我希望 div one 看起来像没有包装器的 div two。

答:

0赞 A Haworth 10/24/2021 #1

您可以将背景图像放在伪元素上并对其进行定位,如果它没有其他设置了位置的更近的祖先,则为其提供身体的尺寸。

请注意,此代码段为元素设置了较窄的宽度,以便它在 SO 代码段系统中显示为较窄,否则它在问题中给出的代码段中看起来没问题。

div.one {
  width: 114px;
  margin: auto;
}
div.one::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  background-color: #1e1e1e;
  background-image: url("https://www.transparenttextures.com/patterns/circles.png");
  background-attachment: fixed;
}
<div class="one">
  Div one is 114px wide and centered
</div>

评论

0赞 Jeff 10/24/2021
非常接近,非常感谢。我添加了它,它适用于那个 div。问题是,页面上任何其他位于屏幕外且需要相同样式的 div 都无法正确显示。我做了这个小提琴作为示范:jsfiddle.net/9bjq4h1p 我有一种感觉,这是不可能的。clip-path: inset(0 -50rem 0 -50rem)div.one
0赞 Simo Walid 10/24/2021 #2

div {
  width: 1140px;
  margin: auto;
}
   body {

  background-color: #1e1e1e;
  background-image: url("https://www.transparenttextures.com/patterns/circles.png");
  background-attachment: fixed;
}
<div class="one">
  Div one is 1140px wide and centered
</div>
<div>
  <div class="two">
    Div two is 1140px wide and centered with a 100%-width wrapper
    Is it possible to create a full width background without a wrapper on a fixed-width div?
  </div>
</div>

评论

0赞 Jeff 10/24/2021
我认为你是对的。我认为使用标签作为包装器是可靠地做到这一点的唯一方法。body