开发者

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?


Have the right div before the left.

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

Working Example


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>


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.


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/


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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜