开发者

Create a dynamic table-like grid without using tables

I am wondering if it's possible to create a grid-like layout using div's that are dynamically created using PHP.

I am creating a product page that will display all products in a PHP database. I want each product to be housed in a div, and 3 divs to display in a row with as many rows as needed to get through all the products.

Somethin开发者_运维问答g like this:

div              div              div
$row['product1'] $row['product2'] $row['product3']

div              div              div
$row['product4'] $row['product5'] $row['product6']

I would prefer not to use a table. I know how to line divs up using the float and clear properties, but not if they are all being created in a while statement, which makes me think it might not be possible.

So I guess, is this possible without using tables, or should I just stick with that?


This can be done the way you ask, though it isn't the best way. It's entirely possible to identify the <div> positions within columns in a while loop:

// Looping over your results simplified...
$i = 1;
while ($results) {
   if ($i % 3 == 1) {
      $div_class = 'left';
   }  
   else if ($i % 3 == 2) {
      $div_class = 'middle';
   }
   else {
      $div_class = 'right';
   }
   $i++;

   // output, simplified
   echo "<div class='$div_class'>$row_contents</div>";
}

Then use your CSS to float and clear as necessary for the left, middle, right classes.

.left, .middle, .right {
   float: left;
}
.left { clear: left; }
.right { clear: right; }

However,

Given all of this, I still probably wouldn't bother with <div>s. Semantically if this is a list of products, you should be listing them in <li> tags. Then just style the <li> to float: left; and make each one 33% the width of the container so you get 3 per line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜