DEV Community

Nic
Nic

Posted on

Breaking a background out of its container

I recently had an element inside a container. The container had a max-width set. But I needed the background colour of my element to fill the width of the screen. I couldn't change the HTML or the max-width of the container. What to do?

Box shadow

The first thing I did was to remember the video short I'd seen recently from Kevin Powell. In it, he uses a box-shadow to cover the screen in the background colour, then use clip-path to contain the box-shadow.

I tried it, it worked a treat. Until I had to add an absolutely positioned element that starts inside the element but finishes outside of it. The clip-path cut it off. Fortunately, there's another way.

Positioning

All you need is:

.element {
  width: 100vw;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}
Enter fullscreen mode Exit fullscreen mode

We set the element to be so 100% of the width of the screen. This means its left edge starts at the beginning of the container and the right edge is off the right of the screen. We can then use the old positioning trick to make it start at 50% of the way across and move it back by 50% of its width.

Simple when you know how!

Latest comments (0)