1

Started a project involving a 3-column div at the top - 300px/dynamic/350px. The right div falls below the others: http://jsfiddle.net/tspencer103/b49mfno4/1/.

I have tries several suggestions here like http://jsfiddle.net/22YBU/. No luck. Any suggestions? Thanks.

 div #div_1 {
   float: left;
   height: 50px;
   background-color: red;
   width: 300px;
 }

 div #div_2 {
   height: 50px;
   margin: 0px 350px 0px 300px;
   background-color: green;
   text-align: center;
 }

 div #div_3 {
   float: right;
   height: 50px;
   background-color: blue;
   width: 350px;
 }

 <div id="container">
    <div id="div_1">LEFT STATIC 300px</div>
    <div id="div_2">CENTER DYNAMIC</div>
    <div id="div_3">RIGHT STATIC 350px</div>
 </div>
Tim Spencer
  • 131
  • 7

1 Answers1

1

If you're interested in a simple, more modern approach, drop the floats and use flexbox:

HTML (no changes)

<div id="container">
    <div id="div_1">LEFT STATIC 300px</div>
    <div id="div_2">CENTER DYNAMIC</div>
    <div id="div_3">RIGHT STATIC 350px</div>
</div>

CSS

#container { 
  display: flex;
  }

#div_1 {
  background-color: red;
  width: 300px; 
  height: 50px;
  }

#div_2 { 
  background-color: green; 
  text-align: center;  
  height: 50px; 
  flex: 1; /* flexible width */
  }

#div_3 { 
  background-color: blue; 
  width: 350px; 
  height: 50px;
  }

DEMO

Flexbox benefits:

  1. minimal code; very efficient
  2. centering, both vertically and horizontally, is simple and easy
  3. equal height columns are simple and easy
  4. multiple options for aligning elements
  5. it's responsive
  6. unlike floats, which offer limited layout capacity because they were never intended for building layouts, flexbox is a modern (CSS3) technique with a broad range of options.

Note that flexbox is supported by all major browsers, except IE 8 & 9. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add all the prefixes you need, post your CSS in the left panel here: Autoprefixer.

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • Great suggestion. You prefer Flexbox over Bootstrap? Still curious how to "fix" the original code. – Tim Spencer Dec 09 '15 at 22:11
  • Yes, I prefer flexbox over bootstrap (which I've rarely ever used). Flexbox comes directly from the W3C and is, in my view, the future off CSS layouts. – Michael Benjamin Dec 09 '15 at 22:19
  • Here's one way to solve your problem based on your original code... (basically, make child divs `inline-block` and use [**calc**](https://developer.mozilla.org/en-US/docs/Web/CSS/calc) to size flexible div) ... http://jsfiddle.net/b49mfno4/8/ – Michael Benjamin Dec 09 '15 at 22:22
  • 1
    Wow. That was easy :) Thanks, Michael. – Tim Spencer Dec 10 '15 at 00:10