问题
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