Jan Thomä
Jan Thomä

Reputation: 13630

How do you put two divs next to each other so they fill up the available space

I have two divs, the right one is 80px wide the other should fill up the remaining space. So far I tried:

<!DOCTYPE html>

<html>
<head>
    <title>#{get 'title' /}</title>
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
        }

        #left {
            position: relative;
            margin-right: 80px;
            background-color: red;
        }

        #right {
            float: right;
            position: relative;
            text-align: left;
            width: 80px;
            background-color: yellow;
        }
    </style>
</head>
<body>
<div id="left">
    Left
</div>
<div id="right">
    Right
</div>
</body>
</html>

However, the right box is always put below the left box and not right to it. I guess it is because of the margin. I also tried a margin-left: -80px on the right one but this doesnt seem to change anything. So how do I have to change the CSS so that the right div is in the same line as the left div?

Upvotes: 7

Views: 52133

Answers (5)

denis.peplin
denis.peplin

Reputation: 9871

Nowadays it can be done with flex.

Set container's (body in this case) display property to flex, then set width of left div to 100%.

body {
    margin: 0;
    padding: 0;
    display: flex;
}

#left {
    background-color: red;
    width: 100%;
}

#right {
    width: 80px;
    background-color: yellow;
}
<!DOCTYPE html>
<html>
<head>
    <title>#{get 'title' /}</title>
</head>
<body>
<div id="left">
    Left
</div>
<div id="right">
    Right
</div>
</body>
</html>

Upvotes: 1

Sterling Bourne
Sterling Bourne

Reputation: 3372

Alternatively, if you're looking for the LEFT div to remain at a static width and the RIGHT div to expand and contract with the size of the page, you'd use the following code:

.left {
    float: left;
    position: relative;
    width: 80px;
    background-color: red;
}

.right {
    position: relative;
    text-align: left;
    margin-left: 80px;
    background-color: yellow;
}

And the HTML would be...

<div class="left">Left</div>
<div class="right">Right</div>

Upvotes: 3

Sotiris
Sotiris

Reputation: 40096

You can change the position:relative; of #right to position:absolute;top:0;right:0;. This will position the element in the right-top corner of its parent.

Example: http://jsfiddle.net/WaQGW/

Upvotes: 1

Sang Suantak
Sang Suantak

Reputation: 5265

That's because div is a block element, meaning it will always break the flow. What you can do is change both the div's display to inline and float to left.

Upvotes: 2

user142162
user142162

Reputation:

Have the right div before the left.

<div id="right">
    Right
</div>
<div id="left">
    Left
</div>

Working Example

Upvotes: 14

Related Questions