2015-08-29 313 views
0

这很容易to create a simple sidebar with pure CSS侧边栏与纯边缘的边缘?

#page-wrap { 
    position: relative; 
    margin: 0 auto; 
    max-width: 600px; 
} 

#content { 
    margin-right: 200px; 
} 

#sidebar { 
    width: 190px; 
    position: fixed; 
    right: 0; 
    height: 100vh; 
} 

这种解决方案的问题是,#sidebar(红色)坚持窗口并留下巨大的缺口给#content(黄色)如果窗口变大:

enter image description here

我们怎样才能解决这个问题,我们也就是如何使这一差距被添加到侧边栏,而不是到当窗口宽度增长?这里是how we can solve this we JQuery

#sidebar { 
    width: 190px; 
    position: absolute; 
    right: 0; 
    height: 100vh; 
} 

function updateSidebar(sidebar) { 
    sidebar.css('top', $(window).scrollTop()); 
    sidebar.css('height', $(window).height() - 
     sidebar[0].getBoundingClientRect().top); 
} 

updateSidebar($('#sidebar')); 
$(window).on('scroll', function() { 
    updateSidebar($('#sidebar')) 
}); 

是否有可能实现wihthout JavaScript中的一样,用纯CSS即?

回答

2

我认为你正在寻找calc()

在你的榜样,因为#page-wrap#sidebar有固定的宽度,你可以通过设置

left: calc(50% + 110px); 

110px600px/2 - 190px结果使侧边栏贴到网页包裹的右边框。

[Updated fiddle]

1

有一个简单的解释。 A position:Fixed元素需要通过屏幕XY轴定位,而不是来自其相对父亲。该元素位于视口右侧零像素处。

最好的解决办法是改为absolute,但也许你不想要这种行为。

也许你需要研究有关粘定位元素:

http://www.sitepoint.com/css-position-sticky-introduction-polyfills/

+0

我知道如何'位置:fixed'作品,我已经把它改成'absolute'你可能已经从我的第二个代码片段可见。但是'位置:粘性'对我来说是新的,我会给它一个阅读。 – theV0ID

+1

位置:sticky与所有浏览器不兼容。 http://caniuse.com/#search=sticky –

+0

我与您分享了polyfills的链接。 Polyfills可以帮助您与旧版浏览器兼容。祝你好运! –