固定VS绝对定位以进行滚动 [英] fixed VS absolute positioning for scrolling

查看:37
本文介绍了固定VS绝对定位以进行滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在玩一些CSS的绝对和固定属性,遇到了CSS中绝对和相对位置之间的不寻常差异.

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;
}

这是小提琴:小提琴.(请检查CSS中的注释)

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

希望您对此问题进行解释.

Would appreciate an explanation on this issue.

推荐答案

固定的位置意味着该元素固定在视口中-不受滚动影响.您可以在此处了解更多信息: https://css-ricks.com/absolute-relative-fixed-positioining-how-to-the-difference/

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.

查看在此版本中为容器设置高度时会发生什么: http://jsfiddle.net/93ubza81/3/

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.

这篇关于固定VS绝对定位以进行滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆