CSS two divs next to each other
I want to put two <div>
s next to each other. The right <div>
is about 200px; and the left <div>
must fill up the rest of the screen width? How can I do this?
Solution 1:
You can use flexbox to lay out your items:
#parent {
display: flex;
}
#narrow {
width: 200px;
background: lightblue;
/* Just so it's visible */
}
#wide {
flex: 1;
/* Grow to rest of container */
background: lightgreen;
/* Just so it's visible */
}
<div id="parent">
<div id="wide">Wide (rest of width)</div>
<div id="narrow">Narrow (200px)</div>
</div>
This is basically just scraping the surface of flexbox. Flexbox can do pretty amazing things.
For older browser support, you can use CSS float and a width properties to solve it.
#narrow {
float: right;
width: 200px;
background: lightblue;
}
#wide {
float: left;
width: calc(100% - 200px);
background: lightgreen;
}
<div id="parent">
<div id="wide">Wide (rest of width)</div>
<div id="narrow">Narrow (200px)</div>
</div>
Solution 2:
I don't know if this is still a current issue or not but I just encountered the same problem and used the CSS display: inline-block;
tag.
Wrapping these in a div so that they can be positioned appropriately.
<div>
<div style="display: inline-block;">Content1</div>
<div style="display: inline-block;">Content2</div>
</div>
Note that the use of the inline style attribute was only used for the succinctness of this example of course these used be moved to an external CSS file.
Solution 3:
Unfortunately, this is not a trivial thing to solve for the general case. The easiest thing would be to add a css-style property "float: right;" to your 200px div, however, this would also cause your "main"-div to actually be full width and any text in there would float around the edge of the 200px-div, which often looks weird, depending on the content (pretty much in all cases except if it's a floating image).
EDIT: As suggested by Dom, the wrapping problem could of course be solved with a margin. Silly me.
Solution 4:
The method suggested by @roe and @MohitNanda work, but if the right div is set as float:right;
, then it must come first in the HTML source. This breaks the left-to-right read order, which could be confusing if the page is displayed with styles turned off. If that's the case, it might be better to use a wrapper div and absolute positioning:
<div id="wrap" style="position:relative;">
<div id="left" style="margin-right:201px;border:1px solid red;">left</div>
<div id="right" style="position:absolute;width:200px;right:0;top:0;border:1px solid blue;">right</div>
</div>
Demonstrated:
left rightEdit: Hmm, interesting. The preview window shows the correctly formatted divs, but the rendered post item does not. Sorry then, you'll have to try it for yourself.