Search code examples
csshtmlstylespositioning

Trouble positioning divs inside other divs


Right now I have a main div with an id of "wrapper", and inside this div I am trying to make two other divs that take up about the entire width of "wrapper". The first div, "sidebar", is narrow and contains some information I want displayed on the far right of "wrapper". The second internal div I have will be dynamically updated using php and javascript from data inserted by users, id called "maincontent".

I can get them positioned inside "wrapper" fine at first. The problem comes when new content is added in the "maincontent" div. When new content is added the "sidebar" div will move down proportionally to the height of the newly added content.

So, my question is this:

How do I get the two internal divs to maintain their positions on the top of the page while still being able to extend dynamically downward without anything moving around?


Solution

  • you need to float:left your left-content:

    see the css below:

      .wrapper
      {
         margin:0;
         padding:0;
         top:10px;
         width:100%;
         height:500px;
         background-color:yellow;
      }
      .left-content
      {
         position:relative;
         width:20%;
         background-color:red;
         height:100%;
         float:left;
      }
      .main-content
      {
         position:relative;
         width:80%;
         left:20%;
         background-color:green;
         height:100%;
    
      }
    

    where your divs are as below:

    <body>
    <div class="wrapper">
      <div class="left-content">
      </div>
      <div class="main-content">
      </div>
    </div>
    </body>
    

    what's important is, you accurately divide the width of the parent to the child containers

    i.e. total width of child containers <= parent width

    see, you need to learn about position attribute of css-style when you do position:relative for any container, css properties like top, left,right,bottom starts working for them.