简体   繁体   中英

div percentage height does not work as intended - inside fixed div

issue: http://jsfiddle.net/um2b98we/5/

I have a small problem. I try to create a navigation where the child (blue box) div is 75% screen height. I have no problems at all, as long as the parent (green box) is in relative position.

However, when I scroll down, I want the parent to be fixed on top of the screen. However then the child changes the height to 75% of the parent but I need it to keep being 75% height of the screen

for sample code, go to the link above:

#scroll, #header, #one, #two {width: 100%}
#scroll {height: 2000px;}
#one {
    background: red;
    height:50px;
}
#two {
    background: green;
    height:50px;
}
#two.fixed{
    position:fixed;
    top:0;
}
#sub {
    position: absolute;
    height: 75%;
    width: 80%;
    background: blue;
    margin-top:50px;
}

<div id="scroll">
    <div id="header">
        <div id="one"></div>
        <div id="two">
            <div id="sub"></div>    
        </div>
    </div>
</div>

I have been trying to fix it for a long time without any success. I would appreciate the help.

You could give the div height with javascript:

$(window).bind('scroll', function(){
    var windowHeight = $(window).height();
    $('#two').toggleClass('fixed',$(window).scrollTop() > 50);
    $('#sub').css('height',windowHeight *.75);
});

or add it after you applied the fixed class to it:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop(),
    windowHeight = $(window).height();

    if (scroll >= 50) {
        $("#two").addClass("fixed");
        $('#sub').css('height', windowHeight *.75);
    } else {
        $("#two").removeClass("fixed");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM