简体   繁体   English

固定侧栏垂直居中

[英]Fixed sidebar centered vertically

A website I am building has a fixed sidebar on the left at the center of the screen. 我正在建立的网站的屏幕中心左侧有一个固定的侧边栏。 It should always stay at the vertical center of the browser window when the page is scrolled. 滚动页面时,它应始终位于浏览器窗口的垂直中心。

How can I achieve this effect? 我怎样才能达到这种效果? Is there a pure css/html solution? 是否有纯CSS / HTML解决方案?

I thought about updating the sidebars position onscroll, but it is likely to flicker as the css top position gets updated. 我考虑过要更新侧边栏滚动位置,但是随着css顶部位置的更新,它可能会闪烁。 Is there any other solution? 还有其他解决方案吗? I would really like to do this with css only, but I wouldnt mind if jquery would provide the functionality I am looking for. 我真的只想用CSS来做到这一点,但是我不介意jquery是否可以提供我想要的功能。

You probably need to add position: fixed; 您可能需要添加position: fixed; to the css to make it so that it does not move. 到CSS以使其不会移动。

Here's what you are looking for. 这就是您要找的东西。 Please note that mobile browsers will ignore position:fixed so you will need to use some js to make it work for them as well. 请注意,移动浏览器将忽略position:fixed因此您还需要使用一些js使其适用于它们。 Also, make sure that the container's min-height is 200px; 另外,请确保容器的最小高度为200像素;

#sidebar
{
    height: 200px;
    position: fixed;    /* Keep in position on scroll */
    top: 50%;       /* push down 50% of container */
    margin-top: -100px; /* bring back up 50% height of this element */
}

#container
{
    min-height: 200px;
    _height: 200px; /* IE6 always acts as though height is min-height unless overflow: hidden */
}

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

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