-1

I have a centered container and I need to stick two elements to its left and right side, which would act like a background. I can do this simply with :before and :after elements which would be positioned absolutely with left: -<element_width>; and right: -<element_width>. Problem is that I need their position to be fixed and fixed positioning doesn't work relatively to the parent.

Here is a fiddle.

How can I achieve this? I don't mind new-css tricks which don't work in old browsers.

Martin Heralecký
  • 5,649
  • 3
  • 27
  • 65
  • Maybe `position: sticky` is an option. See [**here**](https://stackoverflow.com/q/32262455/3597276) and [**here**](https://stackoverflow.com/q/38812478/3597276) and [**here**](https://stackoverflow.com/q/34984452/3597276). – Michael Benjamin Dec 02 '17 at 16:04

1 Answers1

0

You can use position: fixed and calc to achieve that

Check the updated css below

.content {
    width: 50%;
    height: 2000px;
    margin: 0 auto;
    position: relative;
    background: white;
}

.content:before {
    content: "";
    display: block;
    width: 50px;
    height: 200px;
    position: fixed; //fixed position
    left: calc(50% - 25% - 50px); // used calc to determine the correct position
    background: red;
}

Explanation left: calc(50% - 25% - 50px);

50% is to position the item at the center of the page.

-25% is half the value of the parent container which is 50%

-50px is the width of :before to move it to the left

Quick Note: Most browsers will set the default left and top positions of a fixed position element to be the same left and top of its parent container, so if you used position:fixed without specifying left and top the fixed element will default to its parent element position

Edit: as mentioned in comments above position:sticky will also do the trick but it might give some different behaviour on old browsers and mobile devices.

Amr Labib
  • 3,995
  • 3
  • 19
  • 31