Expand a div to fill the remaining width
Asked Answered
W

21

660

I want a two-column div layout, where each one can have variable width e.g.

div {
  float: left;
}

.second {
  background: #ccc;
}
<div>Tree</div>
<div class="second">View</div>

I want the 'view' div to expand to the whole width available after 'tree' div has filled needed space.

Currently, my 'view' div is resized to content it contains It will also be good if both divs take up the whole height.


Not duplicate disclaimer:

Whelan answered 11/8, 2009 at 12:46 Comment(2)
Either I don't understand the question or I don't understand how you choose the accepted answer, because there both widths and heights are fixed with the inconvenience of overflow hiddenSw
@Sw It is the correct explanation for the behavior, and at the time better solutions like flexbox were not available.Sanbenito
G
1090

The solution to this is actually very easy, but not at all obvious. You have to trigger something called a "block formatting context" (BFC), which interacts with floats in a specific way.

Just take that second div, remove the float, and give it overflow:hidden instead. Any overflow value other than visible makes the block it's set on become a BFC. BFCs don't allow descendant floats to escape them, nor do they allow sibling/ancestor floats to intrude into them. The net effect here is that the floated div will do its thing, then the second div will be an ordinary block, taking up all available width except that occupied by the float.

This should work across all current browsers, though you may have to trigger hasLayout in IE6 and 7. I can't recall.

Demos:

div {
  float: left;
}

.second {
  background: #ccc;
  float: none;
  overflow: hidden;
}
<div>Tree</div>
<div class="second">View</div>
Garnettgarnette answered 19/11, 2009 at 23:16 Comment(16)
What if the content is big enough to overflow the div ?Crazy
This doesn't work in Firefox or Chrome with none div elements set to display:block.Inly
good answer. but why isn't the same principle valid to "float: right"?Gann
@Gann It is valid, if by that you mean "can I use float:right for the sidebar instead?". Totally still works. If you mean "why can't I just use float:right for the main area", it's for the same reason float:left doesn't work - it shrinkwraps the content.Garnettgarnette
If I take-out all css from .left other than height, it still takes-up all remaining width. If I change display to anything other than block it doesn't work. (Firefox 34.0)Arand
No overflow needed, Just put the variable-length div in the last (so it will be computed lastly). See jsfiddle.net/wangzhihao/A8zLY/2258Rangoon
Incorrect. Without 'overflow' (or some other means of triggering a BFC), the variable-length div won't "avoid" the other div. Its text will avoid the floated divs, but its background/border/etc will encompass them, which probably isn't what's wanted.Garnettgarnette
It is important to note, that the order of the children matters. The floating element with fixed width has to be above the other one. Took me too long to figure out, why it didn't worked for me with switched order.Rizas
I wrote an answer explaining why a non-visible overflow of all things triggers a BFC, based on responses given by David and Boris, which can be found here: #9944003 Was my interpretation correct?Kalinda
Is there a way to make both columns always the same height and valign the content? jsfiddle.net/A8zLY/3334Ticker
Yes, use Flexbox. Floats were never meant for this sort of layout, they were just a required hack before Flexbox (and now Grid) existed to do it correctly.Garnettgarnette
the "fixed left" fiddle has the .left box on the right and the .right box on the left, which is pretty confusing at first. :PSmashed
when the flexible part is an input, it won't work, even when setting it to display:block, any ideas?Inefficient
An updated tweak on your fiddle using flexbox, which allows you to have this behavior without having to specify exact widths: jsfiddle.net/xseoa9rkLeucotomy
The link for "the magic of overflow" is no longer valid, the new one is colinaarts-com.herokuapp.com/articles/…Viviparous
Doesn't work if container has width:100% !Atheroma
H
185

I just discovered the magic of flex boxes (display: flex). Try this:

<style>
  #box {
    display: flex;
  }
  #b {
    flex-grow: 100;
    border: 1px solid green;
  }
</style>
<div id='box'>
 <div id='a'>Tree</div>
 <div id='b'>View</div>
</div>

Flex boxes give me the control I've wished css had for 15 years. Its finally here! More info: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Haematothermal answered 28/5, 2015 at 2:38 Comment(2)
Thank you. Can you please explain why do you have flex-grow: 100; instead of flex-grow: 1;?Sherrer
@YevgeniyAfanasyev No particular reason except that's how I like to do it. It allows me to think in percents so if I could do something like set #a to flex-grow:10 and then I'd set #b to flex-grow: 90 so #a would be 10% of the line's width and #b would be 90% of the line's width. If no other elements have a flex width style, then it doesn't technically matter what you put.Haematothermal
M
70

Use the CSS Flexbox flex-grow property to fill the remaining space.

html, body {
  height: 100%;
}
body {
  display: flex;
}
.second {
  flex-grow: 1;
}
<div style="background: #bef;">Tree</div>
<div class="second" style="background: #ff9;">View</div>
Materials answered 6/11, 2016 at 8:12 Comment(0)
T
29

This would be a good example of something that's trivial to do with tables and hard (if not impossible, at least in a cross-browser sense) to do with CSS.

If both the columns were fixed width, this would be easy.

If one of the columns was fixed width, this would be slightly harder but entirely doable.

With both columns variable width, IMHO you need to just use a two-column table.

Travax answered 11/8, 2009 at 12:49 Comment(3)
Table won't be very good in a responsive design where you want the right hand column to slide under the left on small devices though.Clay
There are some responsive design tricks to work with tables: css-tricks.com/responsive-data-tablesGargantuan
I tend now to often design two separate layouts completely and change on a mobile using media queries and display:none; Whilst making as much as possible 100% responsive on a sliding scale sometimes it's nicer to change your design completely for a mobile making use of the touch screen feel and button style.Geraldo
C
25

Use calc:

.leftSide {
  float: left;
  width: 50px;
  background-color: green;
}
.rightSide {
  float: left;
  width: calc(100% - 50px);
  background-color: red;
}
<div style="width:200px">
  <div class="leftSide">a</div>
  <div class="rightSide">b</div>
</div>

The problem with this is that all widths must be explicitly defined, either as a value(px and em work fine), or as a percent of something explicitly defined itself.

Charlean answered 9/3, 2016 at 6:53 Comment(1)
The benefit of this is that it works with input type fields, which the top rated comment wont.Cargian
O
22

Check this solution out

.container {
  width: 100%;
  height: 200px;
  background-color: green;
}
.sidebar {
  float: left;
  width: 200px;
  height: 200px;
  background-color: yellow;
}
.content {
  background-color: red;
  height: 200px;
  width: auto;
  margin-left: 200px;
}
.item {
  width: 25%;
  background-color: blue;
  float: left;
  color: white;
}
.clearfix {
  clear: both;
}
<div class="container">
  <div class="clearfix"></div>
  <div class="sidebar">width: 200px</div>

  <div class="content">
    <div class="item">25%</div>
    <div class="item">25%</div>
    <div class="item">25%</div>
    <div class="item">25%</div>
  </div>
</div>
Offhand answered 13/1, 2014 at 16:22 Comment(2)
This is generally a superior solution because hiding overflow is not always desired.Epencephalon
Per OP: "I want a two-column div layout, where each one can have variable width". In your answer, you have to know the width of the first column, so it's not variable. You might as well set fixed widths on both columns and just float them.Estreat
G
16

Here, this might help...

<html>

<head>
  <style type="text/css">
    div.box {
      background: #EEE;
      height: 100px;
      width: 500px;
    }
    div.left {
      background: #999;
      float: left;
      height: 100%;
      width: auto;
    }
    div.right {
      background: #666;
      height: 100%;
    }
    div.clear {
      clear: both;
      height: 1px;
      overflow: hidden;
      font-size: 0pt;
      margin-top: -1px;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="left">Tree</div>
    <div class="right">View</div>
    <div class="clear" />
  </div>
</body>

</html>
Garlen answered 11/8, 2009 at 13:16 Comment(2)
+1 because your example seems to work, but in my real scenario some how contents from 'view' creep into 'tree' div, as tree div is not 100%, may be some javascript forces it to be small and after height of tree I see view contentsWhelan
In that case, if u know the max-width of the left column, u can either give it a style max-width (does not work in IE) or think of margin-left (beware of double-margin bug on IE) or padding-left.Garlen
E
9

If the width of the other column is fixed, how about using the calc CSS function working for all common browsers:

width: calc(100% - 20px) /* 20px being the first column's width */

This way the width of the second row will be calculated (i.e. remaining width) and applied responsively.

Erase answered 30/10, 2015 at 21:11 Comment(0)
T
4

I don't understand why people are willing to work so hard to find a pure-CSS solution for simple columnar layouts that are SO EASY using the old TABLE tag.

All Browsers still have the table layout logic... Call me a dinosaur perhaps, but I say let it help you.

<table WIDTH=100% border=0 cellspacing=0 cellpadding=2>
  <tr>
    <td WIDTH="1" NOWRAP bgcolor="#E0E0E0">Tree</td>
    <td bgcolor="#F0F0F0">View</td>
  </tr>
</table>

Much less risky in terms of cross-browser compatibility too.

Toshiatoshiko answered 9/12, 2010 at 6:30 Comment(3)
yes, but if everything is being done by css why not this, at least a curiosity if it is possble?Whelan
That is because if you want to put media-queries to put both columns one above the other in small devices, it is impossible with the old table tag. To get this working, you need to apply CSS table styles. So, for nowadays it is better to solve this with CSS if you want a responsive layout for any screen size.Subsistence
Because tables are for tabular content. OP doesn't have tabular content; they have two divs with unknown content inside of them.Sanbenito
B
3

<html>

<head>
  <style type="text/css">
    div.box {
      background: #EEE;
      height: 100px;
      width: 500px;
    }
    div.left {
      background: #999;
      float: left;
      height: 100%;
      width: auto;
    }
    div.right {
      background: #666;
      height: 100%;
    }
    div.clear {
      clear: both;
      height: 1px;
      overflow: hidden;
      font-size: 0pt;
      margin-top: -1px;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="left">Tree</div>
    <div class="right">View</div>
    <div class="right">View</div>
    <div style="width: <=100% getTreeWidth()100 %>">Tree</div>
    <div class="clear" />
  </div>
  <div class="ColumnWrapper">
    <div class="Colum­nOne­Half">Tree</div>
    <div class="Colum­nOne­Half">View</div>
  </div>

</body>

</html>
Barium answered 19/1, 2011 at 9:25 Comment(1)
I want something like a status bar with fixed items on the left, fixed items on the right and one message line that uses all of the left over space. I started with this answer and added my message div AFTER the floats with: height: 20px; white-space: nowrap; overflow: hidden; text-overflow:clipDuteous
F
3

You can try CSS Grid Layout.

dl {
  display: grid;
  grid-template-columns: max-content auto;
}

dt {
  grid-column: 1;
}

dd {
  grid-column: 2;
  margin: 0;
  background-color: #ccc;
}
<dl>
  <dt>lorem ipsum</dt>
  <dd>dolor sit amet</dd>
  <dt>carpe</dt>
  <dd>diem</dd>
</dl>
Facula answered 15/8, 2017 at 16:0 Comment(0)
C
3

flex-grow - This defines the ability for a flex item to grow if necessary. It accepts a unitless value that serves as a proportion. It dictates what amount of the available space inside the flex container the item should take up.

If all items have flex-grow set to 1, the remaining space in the container will be distributed equally to all children. If one of the children has a value of 2, the remaining space would take up twice as much space as the others (or it will try to, at least). See more here

.parent {
  display: flex;
}

.child {
  flex-grow: 1; // It accepts a unitless value that serves as a proportion
}

.left {
  background: red;
}

.right {
  background: green;
}
<div class="parent"> 
  <div class="child left">
      Left 50%
  </div>
   <div class="child right">
      Right 50%
  </div>
</div>
Cureall answered 8/11, 2018 at 14:23 Comment(1)
In your exemple both divs will grow and fill the remaining space. The question asked that one div doesn't grow, and the other fills the remaining space.Atheroma
B
1

A slightly different implementation,

Two div panels(content+extra), side by side, content panel expands if extra panel is not present.

jsfiddle: http://jsfiddle.net/qLTMf/1722/

Byword answered 6/2, 2014 at 11:58 Comment(0)
O
1

You can use W3's CSS library that contains a class called rest that does just that:

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<div class="w3-row">
  <div class="w3-col " style="width:150px">
    <p>150px</p>
  </div>
  <div class="w3-rest w3-green">
    <p>w3-rest</p>
  </div>
</div>

Don't forget to link the CSS library in the page's header:

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

Here's the official demo: W3 School Tryit Editor

Oliver answered 7/8, 2017 at 13:40 Comment(1)
Looks like that just adds "overflow: hidden", which makes it a worse version of the answer already givenReparative
E
0

Im not sure if this is the answer you are expecting but, why don't you set the width of Tree to 'auto' and width of 'View' to 100% ?

Ericerica answered 11/8, 2009 at 12:49 Comment(1)
Because that will put the second float below the first because it's too wide.Travax
D
0

.btnCont {
  display: table-layout;
  width: 500px;
}

.txtCont {
  display: table-cell;
  width: 70%;
  max-width: 80%;
  min-width: 20%;
}

.subCont {
  display: table-cell;
  width: 30%;
  max-width: 80%;
  min-width: 20%;
}
<div class="btnCont">
  <div class="txtCont">
    Long text that will auto adjust as it grows. The best part is that the width of the container would not go beyond 500px!
  </div>
  <div class="subCont">
    This column as well as the entire container works like a table. Isn't Amazing!!!
  </div>
</div>
Discount answered 1/6, 2011 at 9:17 Comment(1)
There is no html reference for the css class .ip and it doesn't work in IE7Memorable
N
0

I wrote a javascript function that I call from jQuery $(document).ready(). This will parse all children of the parent div and only update the right most child.

html

...
<div class="stretch">
<div style="padding-left: 5px; padding-right: 5px; display: inline-block;">Some text
</div>
<div class="underline" style="display: inline-block;">Some other text
</div>
</div>
....

javascript

$(document).ready(function(){
    stretchDivs();
});

function stretchDivs() {
    // loop thru each <div> that has class='stretch'
    $("div.stretch").each(function(){
        // get the inner width of this <div> that has class='stretch'
        var totalW = parseInt($(this).css("width"));
        // loop thru each child node
        $(this).children().each(function(){
            // subtract the margins, borders and padding
            totalW -= (parseInt($(this).css("margin-left")) 
                     + parseInt($(this).css("border-left-width")) 
                     + parseInt($(this).css("padding-left"))
                     + parseInt($(this).css("margin-right")) 
                     + parseInt($(this).css("border-right-width")) 
                     + parseInt($(this).css("padding-right")));
            // if this is the last child, we can set its width
            if ($(this).is(":last-child")) {
                $(this).css("width","" + (totalW - 1 /* fudge factor */) + "px");
            } else {
                // this is not the last child, so subtract its width too
                totalW -= parseInt($(this).css("width"));
            }
        });
    });
}
Nocturne answered 11/3, 2017 at 4:43 Comment(0)
P
0

This is fairly easy using flexbox. See the snippet below. I've added a wrapper container to control flow and set a global height. Borders have been added as well to identify the elements. Notice that divs now expand to the full height as well, as required. Vendor prefixes should be used for flexbox in a real world scenario since is not yet fully supported.

I've developed a free tool to understand and design layouts using flexbox. Check it out here: http://algid.com/Flex-Designer

.container{
    height:180px;
    border:3px solid #00f;
    display:flex;
    align-items:stretch;
}
div {
    display:flex;
    border:3px solid #0f0;
}
.second {
    display:flex;
    flex-grow:1;
    border:3px solid #f00;
}
<div class="container">
    <div>Tree</div>
    <div class="second">View</div>
</div>
Perales answered 12/8, 2018 at 8:6 Comment(7)
did you read ALL the previous answers before adding yours? it seems no ...Sg
as a side note, you don't need to add stretch because it's the default value and no need to make the child element flex container so display:flex is useless for the inner elementsSg
I wonder why the downvote, without any comment. Isn't this answer replying to the question? Why? If trying to help others is penalized I will think twice before my next answer,Litharge
you got two comments after the downvote, it's not enough?Sg
Temari, Did you check out my tool? Don't you think is useful and could help others? Do you think is not related with the question? Where is your answer to this question? I can't see it. What's your role here?Litharge
sorry but an answer is not dedicated to promote you own tools, the answer should answer the question and actually the flexbox answer is already provided twice here so there is no need to repeat itSg
The free tool is one reason among others that make me downvote this question and I gave those reasons, if you want to ignore them you are free ... your answer is already provided twice so you didn't even check the previous answers and your code contains useless things. I could have downvoted and leave without adding any comments but I did the effort to do so because I care about the quality of the site.Sg
E
0

.container{
  display: flex;
    align-items: stretch;
}
.resize_overflow {
    position: relative;
    width: 0;
    overflow: hidden;
  white-space: nowrap;
  word-wrap: normal;
    /* text-overflow: ellipsis; When the end of the line dissolves, the ellipsis loses */
}
.second_fix {
    float: right;
    /* or:
    display: flex;
    align-self: end;*/
}
/* Dissolve the end of the line at the right edge */
.resize_overflow::after {
    content: ""; /* Empty content */
    position: absolute; /* Position relative to parent */
    right: 0; /* Element position */
    top: 0; /* Element position */
    width: 40px;  /* Gradient width */
    height: 100%; /* Parent Height */
    background: -moz-linear-gradient(left, rgba(255,255,255, 0.2), #ff 100%);
    background: -webkit-linear-gradient(left, rgba(255,255,255, 0.2), #ff 100%);
    background: -o-linear-gradient(left, rgba(255,255,255, 0.2), #ff 100%);
    background: -ms-linear-gradient(left, rgba(255,255,255, 0.2), #ff 100%);
    background: linear-gradient(to right, rgba(255,255,255, 0.2), #ff 100%);
}
<div class="container">
    <div class="resize_overflow">Tree</div>
    <div class="second_fix">View</div>
</div>
Ejection answered 14/11, 2022 at 11:56 Comment(0)
T
-1

Have a look at the available CSS layout frameworks. I would recommend Simpl or, the slightly more complex, Blueprint framework.

If you are using Simpl (which involves importing just one simpl.css file), you can do this:

<div class="Colum­nOne­Half">Tree</div>
<div class="Colum­nOne­Half">View</div>

, for a 50-50 layout, or :

<div class="Colum­nOne­Quarter">Tree</div>
<div class="Colum­nThreeQuarters">View</div>

, for a 25-75 one.

It's that simple.

Triglyceride answered 11/8, 2009 at 13:11 Comment(1)
will both columns be variable width?Whelan
B
-6

If both of the widths are variable length why don't you calculate the width with some scripting or server side?

<div style="width: <=% getTreeWidth() %>">Tree</div>

<div style="width: <=% getViewWidth() %>">View</div>
Battleax answered 11/8, 2009 at 12:52 Comment(4)
How does the server know how the client's layout engine will work?Perryperryman
Simple: develop it for 90% of the browsers out there :) IE 7+ , FF3+ and Safari support CSS 3. You could also include the standard IE6 <!--[if lte IE 6]> element. By the way, what browser doesn't support style="width: %" ??Battleax
I don't know how It can be done server side, but yes some javscript may do it but i want to avoid it unless css/html can't do itWhelan
Which it can't. Therefore, if you want both to be dynamic then you have to do it in either script or server side.Battleax

© 2022 - 2024 — McMap. All rights reserved.