如何使用Grid布局让<li>元素拥有自身高度?
解决Grid布局下列表项高度统一的问题
我明白你的需求——你希望每个<li>只占据自身内容所需的高度,而不是被Grid布局强制拉伸成同一行中最高项的高度。这个问题其实是Grid布局的默认行为导致的,不过很容易解决!
首先修正你的HTML结构
先提个小问题:<li>元素必须是<ul>或<ol>的直接子元素,你的代码里<div>直接包裹<li>是不符合HTML语义规范的,而且可能引发不必要的样式问题。我先帮你修正结构:
<div> <ul> <li>industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown </li> <li>Lorem ever since the 1500s, when an unknown </li> <li>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown </li> <li>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </li> <li> unknown </li> <li>Lorem Ipsum is simply dummy text of thver since the 1500s, when an unknown </li> <li>L printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown </li> <li>Lorem Ipsum is simply dummy text of the printing and typesettinry's standard dummy text ever since the 1500s, when an unknown </li> <li>Lorem Ipsum is simply dummy text of Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown </li> <li> when an unknown </li> <li>Lorem </li> </ul> </div>
然后调整CSS实现需求
Grid布局默认会让同一行的网格项自动拉伸到相同高度(align-items: stretch是默认值),我们只需要把这个属性改成align-items: start,就能让每个列表项只占据自身内容的高度。
如果你的Grid容器是<div>,CSS可以这么写:
div { display: grid; grid-template-columns: 1fr 1fr 1fr; align-items: start; /* 关键属性,取消自动拉伸 */ } /* 给ul和li加些基础样式,让布局更清晰 */ ul { list-style: none; margin: 0; padding: 0; display: contents; /* 让ul不成为网格项,直接让li作为网格子元素 */ } li { padding: 8px; border: 1px solid #eee; margin: 4px; }
这里的display: contents是为了让<ul>不成为Grid布局中的一个单独网格项,而是让它的子元素<li>直接成为Grid的子元素,这样我们的三列布局才能正确作用在每个<li>上。
这样调整后,每个<li>就会根据自身内容的多少来决定高度,不会再被强制拉伸成同一行的最高高度啦!
内容的提问来源于stack exchange,提问作者Farna Iordanishvili
相关产品推荐
相关产品推荐

