CSS容器查询无法生效:HTML表格样式未按预期应用
容器查询不生效的原因及修复方案
你的容器查询样式未生效,核心问题是选择器优先级不匹配:全局样式中你使用了table.df-price-table caption这类高特异性的选择器,而容器查询内仅用caption这类低特异性选择器,导致容器查询的样式被全局样式覆盖。
另外需确保你的浏览器支持CSS容器查询(Chrome 105+、Firefox 110+、Safari 16+),旧版本浏览器不支持该特性。
修复后的CSS代码
只需在容器查询内的选择器前添加:scope伪类(指代容器元素本身),让选择器特异性与全局样式匹配,即可让容器查询样式正常生效:
table.df-price-table { border: 1px solid #ccc; border-collapse: collapse; margin: 0; padding: 0; width: 100%; table-layout: fixed; container-type: inline-size; container-name: dftable; } table.df-price-table caption { font-size: 1.5em; margin: .5em 0 .75em; } table.df-price-table tr { background-color: #f8f8f8; border: 1px solid #ddd; padding: .35em; } table.df-price-table th, table.df-price-table td { padding: .625em; text-align: center; } table.df-price-table th { font-size: .85em; letter-spacing: .1em; text-transform: uppercase; } @container dftable (max-width: 600px) { :scope caption { font-size: 1.3em; } :scope thead { border: none; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } :scope tr { border-bottom: 3px solid #ddd; display: block; margin-bottom: .625em; } :scope td { border-bottom: 1px solid #ddd; display: block; font-size: .8em; text-align: right; } :scope td::before { content: attr(data-label); float: left; font-weight: bold; text-transform: uppercase; } :scope td:last-child { border-bottom: 0; } }
替代方案(不使用:scope)
如果不想用:scope,也可以直接在容器查询内的选择器前加上容器类名,确保特异性一致:
@container dftable (max-width: 600px) { .df-price-table caption { font-size: 1.3em; } .df-price-table thead { border: none; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .df-price-table tr { border-bottom: 3px solid #ddd; display: block; margin-bottom: .625em; } .df-price-table td { border-bottom: 1px solid #ddd; display: block; font-size: .8em; text-align: right; } .df-price-table td::before { content: attr(data-label); float: left; font-weight: bold; text-transform: uppercase; } .df-price-table td:last-child { border-bottom: 0; } }
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

