How can I make a div fill up the remaining width?
e.g.
<div id="Main" style="width: 500px;">
<div id="div1" style="width: 100px;"></div>
<div id="div2"></div>
<div id="div3" style="width: 100px; float: right;"></div>
</div>
How can I get div2 to fill up the remainder?
Flexbox solution
Note: Add flex vendor prefixes if required by your supported browsers.
Flex-boxes are the solution - and they're fantastic. I've been wanting something like this out of css for a decade. All you need is to add
display: flex
to your style for "Main" andflex-grow: 100
(where 100 is arbitrary - its not important that it be exactly 100). Try adding this style (colors added to make the effect visible):More info about flex boxes here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Try out something like this:
divs will naturally take up 100% width of their container, there is no need to explicitly set this width. By adding a left/right margin the same as the two side divs, it's own contents is forced to sit between them.
Note that the "middle div" goes after the "right div" in the HTML
Up-to-date solution (October 2014) : ready for fluid layouts
Introduction:
This solution is even simpler than the one provided by
Leigh
. It is actually based on it.Here you can notice that the middle element (in our case, with
"content__middle"
class) does not have any dimensional property specified - no width, nor padding, nor margin related property at all - but only anoverflow: auto;
(see note 1).The great advantage is that now you can specify a
max-width
and amin-width
to your left & right elements. Which is fantastic for fluid layouts.. hence responsive layout :-)note 1: versus Leigh's answer where you need to add the
margin-left
&margin-right
properties to the"content__middle"
class.Code with non-fluid layout:
Here the left & right elements (with classes
"content__left"
and"content__right"
) have a fixed width (in pixels): hence called non-fluid layout.Live Demo on http://jsbin.com/qukocefudusu/1/edit?html,css,output
Code with fluid layout:
Here the left & right elements (with classes
"content__left"
and"content__right"
) have a variable width (in percentages) but also a minimum and maximum width: hence called fluid layout.Live Demo in a fluid layout with the
max-width
properties http://jsbin.com/runahoremuwu/1/edit?html,css,outputBrowser Support
Tested on BrowserStack.com on the following web browsers:
Although a
bit
late in posting an answer, here is an alternative approach without using margins.This method works like magic, but here is an explanation :)\
Fiddle with a similar sample here.
I was looking for the a solution to the opposite problem where I needed a fixed width div in the centre and a fluid width div on either side so I came up with the following and thought I'd post it here in case anyone needs it.
HTML:
CSS:
If changing the width of the
#center
element then you need to update the width property of.fluid
to: