如何在同一页面实现dl/dt/dd元素的两种不同布局显示?
同一页面实现两种不同的
<dl>/<dt>/<dd>布局 当然可以实现!你之前遇到的问题是把同行布局的CSS规则直接写在了全局的dl选择器上,导致所有<dl>元素都被强制应用了这个样式,覆盖了浏览器默认的常规布局。只要把同行布局的样式限定在你定义的singleLines类中,就能让两种布局在页面中共存了。
修复后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0, user-scalable=yes"/> <title> DL/DT/DD Demos </title> <style> main { display: grid; gap: 0.25rem; } .gridCols9 { grid-template-columns: repeat(auto-fit,minmax(12.5rem, 1fr)); } .gridCols7 { grid-template-columns: repeat(auto-fit,minmax(16rem, 1fr)); } .gridCols6 { grid-template-columns: repeat(auto-fit,minmax(18rem, 1fr)); } .gridCols5 { grid-template-columns: repeat(auto-fit,minmax(20rem, 1fr)); } .gridCols4 { grid-template-columns: repeat(auto-fit,minmax(25rem, 1fr)); } .gridCols3 { grid-template-columns: repeat(auto-fit,minmax(33rem, 1fr)); } .gridCols2 { grid-template-columns: repeat(auto-fit,minmax(40rem, 1fr)); } main > fieldset { border: 1px solid black; } .fontInfo { white-space: pre-wrap; font-family: monospace; } h3 { background-color: lightgreen; text-align: center; font-size: 1.2rem; cursor: pointer; margin: 0; padding: 0; } article { margin-top: 0; display: block; } /* 仅对带有singleLines类的dl应用同行布局 */ dl.singleLines { display: grid; grid-template-columns: max-content auto; gap: 0.5rem; /* 可选:增加dt和dd之间的间距,提升可读性 */ } dl.singleLines dt { grid-column-start: 1; } dl.singleLines dd { grid-column-start: 2; margin: 0; /* 移除dd默认的外边距,让布局更整齐 */ } </style> </head> <body> <main class="gridCols4"> <fieldset> <legend> Normal </legend> <article><h3>DL/DT/DD Display</h3></article> <dl> <dt>Mercury</dt> <dd>Mercury (0.4 AU from the Sun) is the closest planet to the Sun and the smallest planet.</dd> <dt>Venus</dt> <dd>Venus (0.7 AU) is close in size to Earth, (0.815 Earth masses) and like Earth, has a thick silicate mantle around an iron core.</dd> <dt>Earth</dt> <dd>Earth (1 AU) is the largest and densest of the inner planets, the only one known to have current geological activity.</dd> </dl> </fieldset> <fieldset> <legend> Modified </legend> <article><h3>DL/DT/DD Display</h3></article> <dl class="singleLines"> <dt>Mercury</dt> <dd>Mercury (0.4 AU from the Sun) is the closest planet to the Sun and the smallest planet.</dd> <dt>Venus</dt> <dd>Venus (0.7 AU) is close in size to Earth, (0.815 Earth masses) and like Earth, has a thick silicate mantle around an iron core.</dd> <dt>Earth</dt> <dd>Earth (1 AU) is the largest and densest of the inner planets, the only one known to have current geological activity.</dd> </dl> </fieldset> </main> </body> </html>
核心修改说明
- 限定样式作用范围:把原来全局的
dl、dt、dd选择器,改成dl.singleLines、dl.singleLines dt、dl.singleLines dd这样的类选择器组合,确保只有添加了singleLines类的<dl>才会应用同行布局。 - 优化布局细节:给
dl.singleLines dd移除了浏览器默认的外边距,避免同行布局出现不必要的空白;同时添加了gap属性,让dt和dd之间的间距更合理。 - 保留原生布局:没有添加类的普通
<dl>会自动使用浏览器默认的常规布局(dt在上,dd在下换行显示)。
这样调整后,页面左侧的Normal区域会展示你想要的常规多行布局,右侧的Modified区域则会展示dt和dd同行的布局,两种效果完美共存。
内容的提问来源于stack exchange,提问作者jmrker
相关产品推荐
相关产品推荐

