Welcome to OStack Knowledge Sharing 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 Answer

0 votes
by (71.8m points)

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

transform: translateX(0)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...