我有一个包含人名的MySQL表。使用PHP,最好的方式是将这些名称划分为3列显示。
这可以使用一个超文本标记语言表格来实现,但是是否可以只使用<div>的表格来实现呢?
我听说这可以使用%运算符来完成。这是最好的方式吗?如何做到?
发布于 2011-08-21 22:49:56
您可以使用模运算符来完成此操作,但实际上只使用CSS也是可能的。
使用display: inline-block,您可以获得良好的列效果。看看this JSFiddle here吧。我之所以使用JavaScript只是因为我懒惰;在您的例子中,<div>列表将由PHP生成。如果您想将它们限制在某个宽度内,只需将它们放在一个具有固定宽度的容器<div>中即可。
我已经提出了一个使用表的解决方案,这确实是您应该做的(您还没有给出任何特殊用例)。下面是代码,以及一个有效的演示here。
$columns = 4; // The number of columns you want.
echo "<table>"; // Open the table
// Main printing loop. change `30` to however many pieces of data you have
for($i = 0; $i < 30; $i++)
{
// If we've reached the end of a row, close it and start another
if(!($i % $columns))
{
if($i > 0)
{
echo "</tr>"; // Close the row above this if it's not the first row
}
echo "<tr>"; // Start a new row
}
echo "<td>Cell</td>"; // Add a cell and your content
}
// Close the last row, and the table
echo "</tr>
</table>";最后,我们有了以列为中心的布局,这一次回到了CSS,这里有一些div;这应该放在一个单独的文件中,而不是内联。
<?php
$rows = 10; // The number of columns you want.
$numItems = 30; // Number of rows in each column
// Open the first div. PLEASE put the CSS in a .css file; inline used for brevity
echo "<div style=\"width: 150px; display: inline-block\">";
// Main printing loop.
for($i = 0; $i < $numItems; $i++)
{
// If we've reached our last row, move over to a new div
if(!($i % $rows) && $i > 0)
{
echo "</div><div style=\"width: 150px; display: inline-block\">";
}
echo "<div>Cell $i</div>"; // Add a cell and your content
}
// Close the last div
echo "</div>";
?>https://stackoverflow.com/questions/7138954
复制相似问题