You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Thymeleaf将列表中n个元素渲染为3列布局

实现方案

这里提供两种常用实现方式,可根据你的业务场景选择:


方案一:CSS 实现(优先推荐,改动最小)

直接用CSS Grid或Flex布局实现3列,不需要修改过多Thymeleaf逻辑,后续调整列数只需要改CSS参数即可。
首先调整原HTML的结构,把循环移到列表项上,不要给每个技能单独套外层容器:

<section>
    <div class="sectionTitle">
        <h1>核心技能</h1>
    </div>
    <div class="sectionContent">
        <ul class="skill-list">
            <li th:each="skill : ${userProfile.getUserSkills()}" th:text="${skill.getSkillName()}">[技能名称]</li>
        </ul>
    </div>
    <div class="clear"></div>
</section>

然后添加对应样式:

/* Grid 版本,兼容性较好,写法简洁 */
.skill-list {
    list-style: none;
    padding: 0;
    margin: 0;
    display: grid;
    /* 核心配置:3等分列 */
    grid-template-columns: repeat(3, 1fr);
    /* 行、列间距,可自行调整 */
    gap: 12px 24px;
}

/* 兼容旧版浏览器的Flex版本,可按需替换 */
/*
.skill-list {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-wrap: wrap;
}
.skill-list li {
    width: 33.33%;
    box-sizing: border-box;
    padding-right: 24px;
    margin-bottom: 12px;
}
*/

方案二:Thymeleaf 逻辑切割(适合需要独立列容器的场景)

如果你的UI要求每一列是独立的模块(比如有单独的背景、边框),可以用Thymeleaf的迭代索引把列表切割为3组,分别渲染到3个列容器中:

<section>
    <div class="sectionTitle">
        <h1>核心技能</h1>
    </div>
    <div class="sectionContent">
        <!-- 循环生成3个列容器 -->
        <div class="skill-column" th:each="colIndex : ${#numbers.sequence(0,2)}">
            <ul>
                <li th:each="skill, stat : ${userProfile.getUserSkills()}"
                    <!-- 按索引分配到对应列:每3个元素为一组 -->
                    th:if="${stat.index / 3 == colIndex}"
                    th:text="${skill.getSkillName()}">[技能名称]</li>
            </ul>
        </div>
    </div>
    <div class="clear"></div>
</section>

添加列布局样式:

.skill-column {
    float: left;
    width: 33.33%;
    box-sizing: border-box;
    padding-right: 24px;
}

内容的提问来源于stack exchange,提问作者Shiru99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 00:00:01