Thomas Thomas - 2 months ago 7
CSS Question

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!

Answer

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>