Thomas
Thomas

Reputation: 957

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!

Upvotes: 2

Views: 670

Answers (2)

Ryanthehouse
Ryanthehouse

Reputation: 301

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>

Upvotes: 0

DaniP
DaniP

Reputation: 38252

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>

Upvotes: 2

Related Questions