Flux RSS des billets

DotMG's joblog

Work hard at whatever you do! (Ecc. 9. 10a)
Sidebar using floating div
Publié le 25 Sep 2012, 12:14 pm dans html, css
One of the first advices I heard when doing my job as webmaster is to never use tables other than to list tabular data. On this work, I had to present two columns, they should have the same height, their width are fixed. On the left, I should have one column, grey background, 200px width that I call #sidebar, and on the right, another column, white background, 600px width that I call #main_content. These two block should have the same height, equal to the bigger one. With a table, the job would be very easy :
/* CSS: */
#sidebar {
 width: 200px;
 background: #ccc;}
#main_content {
 width: 600px;
 background: #fff;}
<table><tr>
<td id="sidebar"></td>
<td id="main_content"></td>
</tr></table>
With floating divs, this was my first try:
/* CSS: */
#sidebar {
 width: 200px;
 background: #ccc;
 float: left;
 min-height: 800px;}
#main_content {
 width: 600px;
 background: #fff;}
<div id="sidebar"></div>
<div id="main_content"></div>
Unfortunately, CSS3 doesn't have a rule to force the height of one block to be equal to the height of another. And I didn't want to experiment display:table-cell. The solution I found is to let the sidebar have the height it wants, as the min-height was totally useless here, so I removed background and min-height. To make my sidebar have a background color that would fill all the height, I had to put a parent div.
/* CSS */
#parentdiv {
  background: url('grey.png') repeat-y; }
#sidebar {
  width: 200px;
  float: left; }
#main_content {
  width: 600px; }
.closing {
  clear: both; }
<div id="parentdiv">
  <div id="sidebar"></div>
  <div id="main_content"></div>
  <div class="closing"></div>
</div>
The grey background of the sidebar had to be done on the parentdiv, using an image that fills only 200px on the left. But, hey, the height of the parentdiv is not what we think, because some of the child div is floating. Using the <div class="closing"> which is styled clear:both; fixes this. This div has no content, it serves just to fix the height of the parentdiv.
Les commentaires sont fermés pour ce billet.