Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a div's width stretch between two divs

Tags:

html

css

My current problem is that I have three div elements; one floated left, one floated right, and one between those two. I want the center div to automatically stretch to the max width of the width available between the two divs.

HTML

<div id="contain">
    <div id="left">1</div>
    <div id="filler"></div>
    <div id="right">2</div>
</div>

CSS

#left {
    text-decoration: none;
    display: inline-block;
    float: left;
    width: auto;
    padding: 0px 20px 0px 20px;
    height: 45px;
    text-align: center;
    line-height: 300%;
    background: #FF9000;
    color: #FFFFFF;
}
#navFiller {
    display: inline-block;
    position: fixed;
    float: left;
    width: auto;
    height: 45px;
    background: #FF9000;
}
#right {
    text-decoration: none;
    display: inline-block;
    float: right;
    width: auto;
    padding: 0px 20px 0px 20px;
    height: 45px;
    text-align: center;
    line-height: 300%;
    background: #FF9000;
    color: #FFFFFF;
}
#contain {
    width: 100%;
    height: 45px;
    padding: 0;
    margin: 0;
    display: inline;
}

Jsfiddle of project:

http://jsfiddle.net/msEBU/

like image 702
Burn_E99 Avatar asked Feb 14 '14 14:02

Burn_E99


1 Answers

If you add your filler element after the floated elements, and then change up its styles a little bit (including giving the style-block the correct id), you can get what you're going for:

#left {
  display: inline-block;
  float: left;
  padding: 0px 20px 0px 20px;
  height: 45px;
  text-align: center;
  line-height: 300%;
  background: #FF9000;
  color: #FFFFFF;
}
#filler {
  display: block;
  float: none;
  height: 45px;
  background: #F00;
}
#right {
  display: inline-block;
  float: right;
  padding: 0px 20px 0px 20px;
  height: 45px;
  text-align: center;
  line-height: 300%;
  background: #FF9000;
  color: #FFFFFF;
}
#contain {
  width: 100%;
  height: 45px;
  padding: 0;
  margin: 0;
  display: inline;
}
<div id="contain">
  <div id="left">1</div>
  <div id="right">2</div>
  <div id="filler">m</div>
</div>

OR, simulate a table:

 #contain {
   width: 100%;
   padding: 0;
   margin: 0;
   display: table;
 }
 #left,
 #right {
   text-decoration: none;
   display: table-cell;
   width: 5%;
   text-align: center;
   background: #FF9000;
   color: #FFFFFF;
   padding: 2% 0;
 }
 #filler {
   display: table-cell;
   width: auto;
   background: #F00;
 }
<div id="contain">
  <div id="left">1</div>
  <div id="filler">m</div>
  <div id="right">2</div>
</div>

Both methods have their benefits. It's up to you which is right for you.

like image 131
George Avatar answered Sep 29 '22 21:09

George