marius2k12
marius2k12

Reputation: 1101

2 Divs, variable size and fixed margin inbetween

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

Upvotes: 3

Views: 348

Answers (3)

Mr_Green
Mr_Green

Reputation: 41822

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

Upvotes: 2

moberemk
moberemk

Reputation: 1625

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;
}

Upvotes: 3

user2477462
user2477462

Reputation: 117

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;
}

Upvotes: 0

Related Questions