如何将SQL数据横向排列?每行显示6条后自动换行
问题:SQL查询结果横向排列,每行显示6条记录
从phpMyAdmin获取的SQL数据目前为纵向排列,需要调整为每行显示6条记录,满6条后自动换行。尝试仅通过CSS调整布局无效,新数据会自动向下堆叠。
现有代码
PHP代码
<?php $records = mysqli_query($conn,"SELECT * FROM artists ORDER BY title"); while ($data = mysqli_fetch_array($records)) { ?> <td> <div class="grid-artists"> <div class="column-artists"> <div class="poster"> <?php echo '<img class="round" src="'.$data["img"].' " width="150" height="150"/>'; ?> <br> <br><td><?php echo $data['title']; ?></td><br> <br> </div> </div> </div> </td> <?php } ?>
CSS代码
.poster { width: 150px; background:rgba(59, 59, 59, 0.5); margin: 10px; padding:10px; color: aliceblue; text-align: center; border-radius: 10px; } .grid-artists { display: grid; grid-template-columns: min-content; overflow: hidden; } .column-artists { border: 1px solid rgba(255, 0, 0, 0.8); float: left; font-size: 20px; text-align: center; }
解决方案
1. 修正HTML结构
- 移除循环内的
<td>标签(非表格场景无需使用) - 将所有艺术家卡片放在同一个
grid-artists容器内,而非每个卡片单独嵌套容器 - 修正标题部分的错误
<td>标签,改为<div>或直接文本
2. 调整CSS布局
使用Grid布局设置固定6列,自动实现每行6个元素、满行换行的效果。
修改后的完整代码
PHP代码
<?php $records = mysqli_query($conn,"SELECT * FROM artists ORDER BY title"); ?> <!-- 外层网格容器 --> <div class="grid-artists"> <?php while ($data = mysqli_fetch_array($records)) { ?> <div class="column-artists"> <div class="poster"> <img class="round" src="<?php echo $data["img"]; ?>" width="150" height="150"/> <br><br> <div><?php echo $data['title']; ?></div> <br> </div> </div> <?php } ?> </div>
CSS代码
.poster { width: 150px; background:rgba(59, 59, 59, 0.5); margin: 10px; padding:10px; color: aliceblue; text-align: center; border-radius: 10px; } /* 外层网格容器:设置6列,自动适配宽度 */ .grid-artists { display: grid; grid-template-columns: repeat(6, 1fr); gap: 10px; /* 元素之间的间距 */ padding: 10px; } .column-artists { border: 1px solid rgba(255, 0, 0, 0.8); font-size: 20px; text-align: center; }
补充说明
- 原代码问题:每个艺术家卡片单独嵌套
grid-artists容器,且错误使用表格标签<td>,导致元素只能纵向排列 - 若需响应式布局,可添加媒体查询调整列数,比如小屏幕显示3列:
@media (max-width: 992px) { .grid-artists { grid-template-columns: repeat(3, 1fr); } }
内容的提问来源于stack exchange,提问作者GordonBednarz
相关产品推荐
相关产品推荐

