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

Time:10-24

Is it possible to make div one look like div two without a wrapper? e.g. Extend the background image to fill 100% of the horizontal screen?

Here is a fiddle demonstrating my question

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I was thinking border-image could be a solution, but not sure. I was also messing around with clip-path: inset(0 -50rem 0 -50rem), but I can't seem to make the background-image show outside of the div's boundaries.

CodePudding user response:

You can put the background image on a pseudo element and position that and give it the dimensions of the body if it has no other closer ancestors which have position set.

Note, this snippet has set a narrower width for the element just so that it shows as narrower in the SO snippet system otherwise it looked OK in the snippet given in the question.

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  •  Tags:  
  • css
  • Related