3

I would like to have two divs sit next to each other. Both divs have their width set to a certain percentage. Between the two divs I want a fixed width margin of 20px. The width of div1 and div2 and the 20px margin should add up to 100% of the available space. (See screenshot below)

Heres a basic jsfiddle to get started: jsfiddle

code for jsfiddle link to work

Is this possible without javascript?

what i want

j08691
  • 204,283
  • 31
  • 260
  • 272
marius2k12
  • 1,041
  • 1
  • 18
  • 32
  • 1
    This kind of layout has always been tricky to me. Generally I would have "column" divs which span the entire width (30% and 70% respectively, floated left) but with a padding-right of 20px. Then the last column could have a padding-right of 0px. Also, have you considered CSS frameworks like Twitter Bootstrap, Zurb Foundation, or Yahoo!Pure? I hated the idea of a framework but once I used one, I'll NEVER go back. :) – trnelson Jun 19 '13 at 16:57
  • @moberemk Does the trick perfectly, but check [this SO question](http://stackoverflow.com/questions/7190768/css-fluid-columns-fixed-margins-the-holy-grail-of-holy-grails) too. – scumah Jun 19 '13 at 17:00

3 Answers3

3

Easiest, safest way I know to do something like this is a nested <div>, using the outside div as a container for layout purposes. See here: http://jsfiddle.net/u7VzB/1/

HTML

<div id="container">
    <div id="div1">div#1</div>
    <div id="div2">
        <div>div#2 inner</div>
    </div>    
</div>

CSS:

#container
{
    color: white;
    margin-top: 50px;
}
#div1
{
    float: left;
    width: 30%;
    background-color: black;
}
#div2
{
    float: left;
    width: 70%;
}
#div2 > div {
    margin-left: 20px;   
    background-color: blue;
}
j08691
  • 204,283
  • 31
  • 260
  • 272
moberemk
  • 1,597
  • 1
  • 18
  • 39
2

You can also do something like this without disturbing HTML code:

#container {
    color: white;
    margin-top: 50px;
    position: relative;
}
#div1 {
    float: left;
    width: 30%;
    background-color: black;
}
#div2 {
    float: left;
    position:absolute;
    left: 30%;
    margin-left: 20px;
    right: 0px;
    background-color: blue;
}

Working Fiddle

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
0

try by setting float left, right and reduce the width

#container
{
    color: white;
    margin-top: 50px;
}
#div1
{
    float: left;
    width: 29%;
    background-color: black;
}
#div2
{
    float: right;
    width: 69%;
    background-color: blue;
}
user2477462
  • 117
  • 6
  • 1
    that would leave 2% inbetween. I want the margin inbetween to always be exactl 20px - not 2% – marius2k12 Jun 19 '13 at 16:57
  • Like Marius said, this wouldn't work in all cases; 2% of, say a 1300px div wouldn't work. See my solution for an example of a scalable answer. – moberemk Jun 19 '13 at 16:59