简体   繁体   中英

A fixed div that stays within its parent's width?

Here's a simplified version of my homepage:

<div class="main">
    <div class="content"> all the content of my website </div>
    <div class="nav"> fixed on the screen and always visible </div>
</div>

And here's the corresponding css:

.main {
    max-width: 500px;
    height: 2000px;
    margin: auto;
    background-color: grey;
}

.nav {
    width: 100px;
    height: 100px;
    background-color: blue;
    position:fixed;
    right: 0; /* that's the issue */
}

I'd like the fixed element to stay within it's parent (touching the right edge of its parent). But right now it's touching the right border of the screen.

Any idea how to fix this? Thanks!

You can add an extra item to simulate the properties of the main container, try this:

 .main { max-width: 500px; height: 2000px; margin: auto; background-color: grey; } .nav { position:fixed; max-width:500px; width:100%; } .nav > div{ width: 100px; height: 100px; background-color: blue; float:right; }
 <div class="main"> <div class="content">all the content of my website</div> <div class="nav"><div>fixed on the screen and always visible</div></div> </div>

position: fixed is described as, "The element is positioned relative to the browser window". You can use Javascript to accomplish this effect, here is how you do it with jQuery, for example:

 $(window).scroll(function() { var y = $(window).scrollTop(); $(".nav").css('top', y); });
 .main { max-width: 500px; height: 4000px; margin: auto; background-color: grey; position: relative; } .nav { width: 100px; height: 100px; background-color: red; position: absolute; right: 0; /* that's the issue */ }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="main"> <div class="content"> parent </div> <div class="nav"> fixed to parent width </div> </div>

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