Daniel Williams
Daniel Williams

Reputation: 2317

Auto-sizing nested divs

If you look at the code below

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<body>

<style type="text/css">

    #div1 {  border:1px solid red; overflow:hidden;  }
    #div1 ul {  list-style-type:none; margin:0; padding:0;  }
    #div1 li {  display:inline; float:left;  }
    #div2 {  background-color:pink; width:100%; height:40px;  }
    #div3 {  background-color:yellow; width:40px; height:40px;  }

</style>

<div id="div1">
<ul>
   <li><div id="div2">div2</div3></li>
   <li><div id="div3">div3</div3></li>
</ul>
</div>

</body>
</html>

I'm trying to get DIV2 to take up the remaining width of the parent div, once the 40px width of DIV3 has been assigned.

Is this possible?

Upvotes: 0

Views: 62

Answers (2)

Brandon Gano
Brandon Gano

Reputation: 6710

A block-level element--like <div> or <li> or anything with display:block--will automatically absorb the available width. Something like this should work:

#div1 {
  border: 1px solid red;
  overflow: hidden;
}
#div2 {
  background-color: pink;
  height: 40px;
}
#div3 {
  background-color: yellow;
  float: right;
  width: 40px;
  height: 40px;
}
<div id="div1">
  <div id="div3">div3</div>
  <div id="div2">div2</div>
</div>

Note that the floated content will need to be placed first in order for this approach to work.

Upvotes: 0

haxxxton
haxxxton

Reputation: 6442

My suggestion would be to use display:table and display:table-cell on the ul and li respectively, rather than float and display:inline. To make life easier, i have moved the id's to the li elements rather than the divs

html

<div id="div1">
<ul>
   <li id="div2"><div>div2</div></li>
   <li id="div3"><div>div3</div></li>
</ul>
</div>

CSS

#div1 {  border:1px solid red; overflow:hidden;  }
#div1 ul {  list-style-type:none; margin:0; padding:0; display:table; width:100%;  }
#div1 li {  display:table-cell;  }
#div2 {  background-color:pink; width:100%; height:40px;  }
#div3 {  background-color:yellow; width:40px; height:40px;  }

JS FIDDLE

Upvotes: 1

Related Questions