Search code examples
csshtmlpositioning

CSS Divs positioning


I'm trying to better understand CSS. Can someone help me out with this. I have the following HTML:

<div class="DivParent">
<div class="Div1"></div>
<div class="Div2"></div>
</div>

I need to position them as shown on this diagram: http://i150.photobucket.com/albums/s99/dc2000_bucket/divs_diagram.png

I wrote the following CSS:

.DivParent
{
    border: 1px solid #000000;
    padding: 0;
    margin: 0;
}
.Div1
{
    border: 4px solid #FF0000;
    padding: 0;
    margin: 0;
    float: left;
}
.Div2
{
    border: 4px solid #00FF00;
    padding: 0;
    margin: 0 0 0 10px;
    float: left;
}

Div1 should first stretch horizontally to the right. Div2 should not stretch at all. It can be pushed to the right by Div1 until there's no more room for Div2 to go to the right. After that the Div1 should start growing down (or vertically).

The above works if both Divs are not wide enough, but then Div2 simply gets pushed underneath Div1. How do I keep Div2 always to the right off Div1?


Solution

  • You could do this

    1. give the parent div a fixed width. Use overflow:hidden; to contain the divs
    2. change the floats on the inside divs to display:inline-block;
    3. set width on a the right div
    4. set a max-width on the left div

      .DivParent{
          border: 1px solid #000000;
          padding: 0;
          margin: 0;
          overflow:hidden;
          width:550px;
      }
      
      .Div1{
          border: 4px solid #FF0000;
          padding: 0;
          margin: 0;
          max-width:400px;
          display:inline-block;
      }
      
      .Div2{
          border: 4px solid #00FF00;
          padding: 0;
          margin: 0 0 0 10px;
          width:120px;
          display:inline-block;
          vertical-align:top;
          height:100px;
      }
      

    Example: http://jsfiddle.net/P6SJq/