Vincent Vincent - 6 months ago 9
CSS Question

How to position a div left to another div and top fixed to body?

I would like to add a menu left to a div but fixed relative to the top of the body. So when I scroll the div, the left menu sticks to the screen.



.container {
position: relative;
width: 70%;
margin-right: auto;
margin-left: auto;
height: 1300px;
background-color: grey;
}
.menu_fixed_left {
position: absolute;
left: -50px;
width: 50px;
margin-top: 100px;
z-index: 2;
background-color: silver;
}
ul {
list-style-type: none;
padding: 15px;
}

<body>
<div class="container">
<div class="menu_fixed_left">
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
</div>
Container
</div>
</body>





Here is the fiddle.

Answer

You will have to follow some steps:

  • First of all, you will have to display your menu as fixed.

  • Second, to position it on the top of the body, you will have to use top: 0 (or you can change it to your desired top taking as reference the body tag).

  • As the content div occupy the 70% of the width of the screen with margin: auto it means that it has 15% (30% that is not occupy and the same at each side, 30%/2 = 15%) of the screen on each side so you will have to use calc to rest to the 15% of each side, the 50px that occupy your menu.

  • Remove the default margin of your body tag.

Updated JSFiddle.