简体   繁体   中英

How to fix the position of a sticky sidebar when screen width is small?

I'd like to position a sticky sidebar to the right side of a main panel. The sticky sidebar should be 'sticky' that when scrolling down to the top of itself, the sidebar would determine the position and stick to the top of the page, instead of scrolling up.

I've partially done it here: https://codesandbox.io/s/gallant-saha-zgmnw

Now my problem is: as shown in the fiddle, in the sidebar class, with position: sticky and right: 15rem , the sidebar only works in wide screen width. If screen width shrank, the sidebar component would keep 15rem to right and position incorrectly. Shrink the page and see the wrong behaviour.

I know that setting a fixed 15rem to right is probably wrong, how can I keep the sidebar to the right of the main panel while screen width is shrunk to a certain width?

I think you might want to look into using media queries on your css to detect different screen sizes and change the "right" property on the sidebar accordingly.

Let's assume you have a breakpoint set at 600px, a media query for that breakpoint would be something like this:

@media only screen and (max-width: 600px) {
  .sidebar {
    &-fixed {
      right: 0px;   
    }
  }
}

That means that when the screen size is smaller than 600px width, the right property on your sidebar would be set to 0px.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM