如何在Hugo模板中根据页面宽度动态调整列数?
Hugo Universal主题功能列表自适应列数实现方案
问题背景
使用Hugo Universal主题(及其他同类主题)时,通过配置[params.features]的cols参数设置功能列表列数,但该参数是固定值,无法随页面宽度自适应调整。尝试用CSS媒体查询定义--col变量,但模板无法直接调用该变量,需要寻找自适应实现方案。
解决方案
方案1:纯CSS Grid布局实现自适应(推荐)
无需修改模板或使用JS,直接通过CSS媒体查询控制列数:
- 先移除模板中硬编码的列数相关属性(比如模板里的
cols="{{ .Site.Params.features.cols }}"这类代码) - 添加以下CSS:
.features-list { display: grid; gap: 1rem; /* 可根据需求调整间距 */ } /* 小屏(手机):2列 */ @media (max-width: 767px) { .features-list { grid-template-columns: repeat(2, 1fr); } } /* 中屏(平板):3列 */ @media (min-width: 768px) and (max-width: 1199px) { .features-list { grid-template-columns: repeat(3, 1fr); } } /* 大屏(桌面):4列 */ @media (min-width: 1200px) { .features-list { grid-template-columns: repeat(4, 1fr); } }
解决::before空网格单元格问题
如果出现神秘的空单元格,大概率是主题CSS给.features-list添加了::before伪元素导致的,直接隐藏即可:
.features-list::before { display: none !important; }
或者检查模板结构,确保.features-list的直接子元素只有功能项,没有多余的空标签或伪元素。
方案2:JS动态控制列数(兼容原有模板逻辑)
如果需要保留模板中基于cols参数的布局逻辑,可通过JS根据屏幕宽度动态切换列数类:
- 在模板中给功能列表容器添加基础类:
<div class="features-list" id="features-container"> {{ range .Site.Params.features.items }} <!-- 功能项内容 --> {{ end }} </div>
- 添加JS代码:
function updateFeatureCols() { const container = document.getElementById('features-container'); if (!container) return; const viewportWidth = window.innerWidth; let targetCols = 2; if (viewportWidth >= 768 && viewportWidth < 1200) { targetCols = 3; } else if (viewportWidth >= 1200) { targetCols = 4; } // 移除旧列数类,添加新类 container.classList.remove('cols-2', 'cols-3', 'cols-4'); container.classList.add(`cols-${targetCols}`); } // 初始化+监听窗口 resize window.addEventListener('load', updateFeatureCols); window.addEventListener('resize', updateFeatureCols);
- 对应CSS类定义:
.cols-2 { grid-template-columns: repeat(2, 1fr); } .cols-3 { grid-template-columns: repeat(3, 1fr); } .cols-4 { grid-template-columns: repeat(4, 1fr); }
方案3:模板+CSS变量结合(进阶)
Hugo模板无法直接读取CSS变量,但可以在模板中输出响应式标记,配合CSS控制:
在模板中给容器添加响应式类:
<div class="features-list responsive-features"> {{ range .Site.Params.features.items }} <!-- 功能项内容 --> {{ end }} </div>
然后用CSS媒体查询控制,逻辑和方案1一致,无需依赖模板的cols参数。
更新记录
在@SirPeople的帮助下接近实现自适应布局,但遇到::before空网格单元格问题,最终通过隐藏伪元素的方案解决。
内容的提问来源于stack exchange,提问作者Vlad Feinstein
相关产品推荐
相关产品推荐

