Fickle Bits

You're doing it wrong.

Making DIVs Stay Next to Each Other

A colleague came to me with a very simple issue yesterday.  He had a table surrounding the area he was working on, and he wanted to have 2 DIVs side-by-side, one of them containing a table.

Here’s what he had:

<table>
 <tr>
  <td>
  
   <div style=”padding: 2px; margin: 2px; border: #ccc; background-color:#eee;”>
    here’s the first div
   </div>

   <div style=”padding: 2px; margin: 2px; border: #ccc; background-color:#eee;”>
    ..and here’s the 2nd
    <table border=1>
     <tr>
      <td>with a table</td>
     </td>
    </table>
   </div>
  </td>
 </tr>
</table>

…which looks like:

here’s the first div
..and here’s the 2nd
with a table

 

He tried a number of things that didn’t work.  Here’s the solution:

DIVs are block level elements that stretch to 100% of the width of the parent container.  So to get them to sit next to each other you first need to give them some room to do so.  Set the width so that they will both fit (be sure to account for border + margin as well).

The next thing to do is set the DIVs to float:left;  This will make them push up next to each other until there is no more room, then they will wrap.

Here it is in action:

 <table>
 <tr>
  <td width=”300”>
   
   <div style=”margin:2px; padding:2px; border: solid 1px #bbb; background-color: #eee; float: left; width: 75px;”>
    here’s the 1st div
   </div>

   <div style=”margin:2px; padding:2px; border: solid 1px #bbb; background-color: #eee; float: left; width: 75px;”>
    ..and here’s the 2nd
    <table border=1>
     <tr><td>with a table</td></tr>
    </table>
   </div>
  </td>
 </tr>
</table>

here’s the 1st div
..and here’s the 2nd
with a table

 

Understanding how floating works is an important part of effective CSS web design.  I may consider some more of these simple examples if they are of help to my readers.

Comments