Search code examples
csspositioncss-float

CSS Auto-height Div doesn't position itself correctly


I'm trying to get a simple page layout where the navbar sits vertically along the right side of the user's window, taking up no more than 20% of the available space. The remaining 80% of space to the left is used for content.

I want the entire page to be resizable, so no matter how big or small the browser window is (within reason), the content will resize to the user's screen. Everything works and resizes great, but there's one problem with the navBar. Here's a CSS excerpt:

body{
    background-color: #111111;
    font-family: Roboto;
    color: #cccccc;
    font-weight: 300;
    font-size: 14pt;
    height: 100%;
}

#content{
    width: 80%;
    float: left;
}

#navBar{
    width: 20%;
    height: 100%;
    background-color: #00C9FF;
    float: left;
    position: absolute;
}

#welcome{
    background-color: #222222;
    text-align: center;
    margin: 1%;
}

The Problem:

  • If I leave the code above as is, the navBar renders on the right side of the screen, as it should, but it is not 100% the height of the browser window. Note it still resizes when the browser window's WIDTH is changed.
  • If I set navBar's position to absolute (position: absolute) the navbar renders exactly how it should render, except it floats to the left side of the browser, basically making it on the complete opposite side of where it should be.

Demo: http://codepen.io/anon/pen/YPyvzO (remove position: absolute to see where the navBar SHOULD render)

I have tried several different things including setting "HTML" in CSS to height: 100% and several different position properties for navbar, all to no avail. I'd like for this to be done only in CSS, but I'm not sure if it's possible.


Solution

  • Add the following:

        position: absolute;
        right: 0;
    

    to #navBar. One thing that took me a long time to understand is that position: absolute overrides everything, even floats.