Search code examples
csshtmldom-traversal

Sidebar on the left of the content but after in the dom tree


I need to put a sidebar on the left of the content.

I had this html:

<div class="sidebar"></div>
<div class="content"></div>

and I solved using:

.sidebar{
    width: 280px;
    float: left
}
.sidebar + .content{
    margin-left: 300px
}

For this example: https://jsfiddle.net/VixedS/fcx2aLLa/

But now my that .content comes before the .sidebar,

<div class="content"></div>
<div class="sidebar"></div>

how can I obtain the same result just using css?

I don't want to loose the remaining space of the body for the width of .content with or without .sidebar.

So please remember that before saying to float the .content to right. Also, I don't know which page has a .sidebar.


Solution

  • This solution is very powerfull. Works for every browser, any device. Also a great way for responsive design and for a third column.

    Update:

    .container {  
      overflow:auto; 
    }
    
    .sidebar {
      width: 280px;
      float: left;
      background: #EEE;
      margin-left: -100%;
    }
    
    .content {
      float: left;
      width: 100%;
    }
    
    .center {
      margin-left: 280px;
    }
    
    .container > div:only-child > div.center {
      margin-left: 0;
    }
    <div class="container">
      <div class="content">
        <div class="center">
          Spaghetti
        </div>
      </div>
      <div class="sidebar">
        Pizza
        <br /> Hobby
      </div>
    </div>