简体   繁体   English

屏幕宽度较小时粘性侧边栏的position如何解决?

[英]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.我想要 position 主面板右侧的粘性侧边栏。 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.粘性侧边栏应该是“粘性”的,当向下滚动到自身顶部时,侧边栏将确定 position 并粘在页面顶部,而不是向上滚动。

I've partially done it here: https://codesandbox.io/s/gallant-saha-zgmnw我在这里完成了部分工作: 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.现在我的问题是:如小提琴所示,在sidebar class 中,带有position: stickyright: 15rem ,侧边栏仅适用于宽屏宽度。 If screen width shrank, the sidebar component would keep 15rem to right and position incorrectly.如果屏幕宽度缩小,侧边栏组件将保持 15rem 向右和 position 错误。 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?我知道将固定的 15rem 设置为右侧可能是错误的,当屏幕宽度缩小到一定宽度时,如何将侧边栏保持在主面板的右侧?

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.我认为您可能想研究在 css 上使用媒体查询来检测不同的屏幕尺寸并相应地更改侧边栏上的“正确”属性。

Let's assume you have a breakpoint set at 600px, a media query for that breakpoint would be something like this:假设您在 600px 处设置了一个断点,该断点的媒体查询将如下所示:

@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.这意味着当屏幕尺寸小于 600px 宽度时,侧边栏上的 right 属性将设置为 0px。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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