Search code examples
csshtmlpositioning

Put divs next to eachother based on left margin to parent


Thing I'm trying to achieve

The picture is what I'm trying to achieve. Basicly I'm trying to make one wrapper div and be able to place a variable number of divs within it, based on the left margin to the lefternmost part of the parent wrapper.

I would like to be able to say something like:

.div1 { margin-left:5%; }
.div2 { margin-left:30%; }
.div3 { margin-left:85%; }

And achieve what is seen in the picture. However, I noticed (which I had assumed would happen), that the divs are unwilling to cooperate; when I add a float:left, they seem to add the margins to eachother (as in div2 gets a margin-left:30% in addition to its 5% left margin and its 10% width, making the div2 appear at 45% from the lefternmost part of the wrapper.

I realize I could just take into account the previous margins, and put the margin-left of div2 to 30%-15%=15% and get the right result, but I'd like to know if there's an approach to just do it with the margin-left?


Solution

  • Don't float them; rather, position them absolutely at the location so that they 'overlap' in a sense; the margins will hold them apart in the way you want.

    Example:

    .green {background-color: green; position: absolute}
    .one {width:10%; margin-left:5%}
    .two {width:20%; margin-left: 30%}
    .three {width:10%; margin-left: 85%}
    

    Demo at:

    http://jsfiddle.net/Mu4GU/