Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

父元素为relative,子组件是absolute,父组件允许滚动的时候,子组件如何固定到父元素顶部?

<div style="height: 300px;width: 100px;position: relative;border: solid;overflow-y: scroll;">
        <div style="height: 500px;background-color: lightgrey;"></div>
        <div style="width: 100%;height: 100px;background-color: lightgreen;position: absolute;top: 0;"></div>
    </div>

父组件由于可以滚动,所以他的实际高度不是300,而是500,子组件相对于父组件top:0固定,固定到了实际高度的top:0,我希望是按他实际高度固定,如何实现?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

如果你想简单点,那直接父元素加一个啥也不干的transform属性:

transform: translateX(0)

然后absolute改为fixed,因为transform元素可以关住fixed元素让fixed相对自身定位而不是根元素。

或者让absolute升一级,成为当前父元素的兄弟元素,而它们共同的父元素使用relative。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...