Gachatar Gachatar - 2 months ago 12
CSS Question

CSS vertical menu on two sides

I'm trying to create a design with two vertical menus on each side of the main content part.
I tried various combinations of inline and relative and fixed positions but can't get it to work.

Fiddle: https://jsfiddle.net/g4vbampm/3/

The menus (red and blue blocks) should be right next to the middle green part (position:fixed put it at the edge of the screen to the left). They should also start at the top of the screen and never move. The height of the middle green part is going to change dynamically with js code.

.app{
text-align:center;
}

.left{
background:red;
width:150px;
height:300px;
display:inline-block;
}

.center{
background:green;
width:300px;
height:auto;
display:inline-block;
}

.right{
background:blue;
width:150px;
height:300px;
display:inline-block;
}


<div class="app">

<div class="left">
menu1<br/>
menu2<br/>
menu3<br/>
</div>

<div class="center">
CONTENT<br/>
a<br/>
a<br/>
a<br/>
a<br/>
a<br/>a<br/>
a<br/>
a<br/>
a<br/>
a<br/>

a<br/>
a<br/>
a<br/>
a<br/>
a<br/>a<br/>
a<br/>
a<br/>
a<br/>
a<br/>
a<br/>
a<br/>
a<br/>
</div>

<div class="right">
menu1<br/>
menu2<br/>
menu3<br/>
</div>


</div>

Answer

The menus (red and blue blocks) should be right next to the middle green part (position:fixed put it at the edge of the screen to the left). They should also start at the top of the screen and never move.

If they should “never move,” then you want position:fixed (unless you want to constantly adapt the position via JavaScript, which is in most cases bad in terms of performance and visual outcome.)

Fixed positioning always takes the viewport as reference point. But you can still use it here, if you calculate the position dynamically.

Your middle element is 300px wide, so the other two elements need to be positioned at 50% + 150px, from the right resp. left (the opposite in each case.)

.left,
.right {
  position: fixed;
  top: 0;
}
.left{
  background:red;
  width:150px;
  height:300px;
  right: calc(50% + 150px);
}
.right{
  background:blue; 
  width:150px;
  height:300px;
  left: calc(50% + 150px);
}

https://jsfiddle.net/g4vbampm/4/

Browser support for calc is pretty good, http://caniuse.com/#search=calc

If you need it to work in browsers that don’t support calc, you can also use a negative margin to offset the elements from the middle,

.left{
  right: 50%;
  margin-right: 150px;
}

https://jsfiddle.net/g4vbampm/7/