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



是否可以在没有包装的情况下使div一看起来像div二?例如,将背景图像扩展到水平屏幕的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>

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

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

注意,这个代码段为元素设置了一个更窄的宽度,只是为了在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>

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>