如何仅用CSS和HTML实现内含<p>元素的等高双列并排Div(模拟双列表格)
当然可以用纯CSS实现对应段落等高的效果!完全不需要依赖JavaScript,我们可以利用CSS Grid的强大特性来解决这个问题,同时还能保留你需要的“同语言文本放在同一个div”的结构,方便后续用prepend添加内容。
解决方案思路
核心思路是让外层容器和两个内部div都使用Grid布局:
- 外层容器设置为两列网格,实现左右div的并排。
- 每个内部div也设置为网格容器,并指定行高为
1fr——这样每一行的高度会自动适配该行中最高的段落,自然让左右对应位置的<p>元素保持等高。
修改后的代码
CSS部分
body { font-family: Consolas,Menlo,"courier new",monospace; font-size: 18px; } .grid-container { display: grid; grid-template-columns: 1fr 1fr; /* 两列各占50%宽度 */ gap: 15px; /* 可选:列之间的间距,按需调整 */ } #div1, #div2 { display: grid; grid-auto-rows: 1fr; /* 所有行均分可用空间,自动匹配最高内容高度 */ } p{ margin-top: 0px; padding-bottom: 3px; padding-left: 3px; margin-bottom: 6px; border-bottom: 1px dashed gray; align-self: start; /* 让文本顶部对齐,避免垂直居中 */ }
HTML部分(无需修改,保持你的原有结构)
<div class="grid-container"> <div id="div2" class="skiptranslate"> <p>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 printer took a galley.</p> <p> the second cell</p> <p> the 3rd cell </p> <p> the 4th cell </p> </div> <div id="div1" > <p> I want this cell's height same as the left "lorem ipsum" cell </p> <p> the second cell</p> <p> the 3rd cell</p> </div> </div>
效果说明
- 左右两个div会自动并排,各占50%宽度。
- 对应位置的
<p>元素会自动保持等高,哪怕其中一个段落内容更长。 - 你依然可以正常使用JavaScript的
prepend方法向任意一个div添加新的<p>元素,Grid布局会自动调整行高,维持对应段落的等高效果。
内容的提问来源于stack exchange,提问作者Thi Hoang
相关产品推荐
相关产品推荐

