fixed VS absolute positioning for scrolling

ぐ巨炮叔叔 提交于 2020-12-20 08:22:30

问题


I was just playing around with some CSS absolute and fixed properties and came across a unusual difference between absolute and relative positioning in CSS.

Basically, when I absolutely position something and the content is more than the height of the window or containing element, the scroll bar appears, but when I change the position to fixed, even though the content is more in height compared to the window, no scroll bars appear.

I have created a test case for this:

HTML:

<div class="page-container">
    <div class="helper">
        <div class="marker red"></div>
        <div class="marker green"></div>
        <div class="marker yellow"></div>
        <div class="marker blue"></div>
    </div>
</div>

CSS:

#slides-container {
    height: 100%;
    width: 100%;
    overflow: hidden;
}
.helper {
    height: 400%;
    width: 20px;
    position: fixed;   /* change this to absolute and the scrollbars appear*/
    top: 0;
    left: 0;
}
.helper .marker {
    height: 25%;
    width: 100%;
}
.marker.red {
    background: red;
}
.marker.green {
    background: green;
}
.marker.yellow {
    background: yellow;
}
.marker.blue {
    background: blue;
}

and here's the fiddle: fiddle. (check the comment in the CSS)

Would appreciate an explanation on this issue.


回答1:


Fixed positioning means that the element is fixed in the viewport - it is not affected by scrolling. You can read more here: https://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/

Since nothing else gives height to your page, then all you see in this case is whatever part of the fixed element fits in your viewport.

See what happens when you set a height to the container in this version: http://jsfiddle.net/93ubza81/3/

.page-content{
height: 3000px;
}

You have scrolling, but the fixed element isn't affected.



来源:https://stackoverflow.com/questions/28916009/fixed-vs-absolute-positioning-for-scrolling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!