Can I make a child scroll and ignore its fixed parent?

丶灬走出姿态 提交于 2020-01-24 15:09:59

问题


I'm trying to make the child of a fixed element ignore its parent's "fixed" property, and instead scroll along with the page. So far, here is my best try, which doesn't work...

CSS:

.main-background {
    position: fixed;
    top: 0;
    z-index: -1;
    background-image: url('');
}    
.header-image {
        position: absolute;
        z-index: 100;
    }

HTML:

<div class="main-background">
<img class="header-image"/>
</div>

To make things clearer, I'm not trying to give an additional scrollbar to the child, I'm just trying to make it scroll with the page as if it was positioned outside the parent.

I foretell that someone will answer "just take the child out of the parent", but that doesn't answer my question: I'm looking for a way to keep the existing HTML structure.

Also, I want to keep "position: fixed" and avoid "background-position: fixed" because this property is really inconsistent on mobile.

Maybe it's not possible, but all help is highly appreciated!


回答1:


It looks like you're going to need some javascript in order to do what you're asking. Here's a solution using jQuery.

$(window).scroll( function(){
    $('.header-image').css('top', -$(window).scrollTop() );
});

https://jsfiddle.net/1xba4dzf/



来源:https://stackoverflow.com/questions/59511534/can-i-make-a-child-scroll-and-ignore-its-fixed-parent

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