为什么 legend
元素不会改变 clientHeight
当你将 ::before
内容放入它时,而 h2
会,即使两者都有 height: auto;显示: block ;
?
let h2 = document.querySelector('h2')
let legend = document.querySelector('legend')
console.log('h2:', h2.clientHeight+'px')
console.log('legend:', legend.clientHeight+'px')
body { padding: 200px 0; }
h2::before,
legend::before {
content: "";
display: block;
height: 150px;
margin-top: -150px;
}
h2, legend {
background-color: rgba(0,0,0,.1);
display: block !important;
height: auto !important;
}
<fieldset>
<h2>Headline 2</h2>
</fieldset>
<fieldset>
<legend>Legend</legend>
</fieldset>
最佳答案
问题实际上与伪元素无关,而是与您在字段集中获得图例这一事实有关,即 "damn near impossible to style" .
您可以尝试对抗字段集及其相关图例元素的浏览器样式(如果您想尝试,我上面链接的文章是一个很好的资源),或者您可以从 HTML 中删除字段集(作为文章提到,尽管字段集是对表单字段集进行分组的最语义方式,但许多人避免使用它们),或者您可以在字段集中使用除图例元素之外的其他元素。
这是一个片段,说明了伪元素与真实元素以及有字段集与没有字段集。可以看到,无论是不是伪元素,图例的高度为0完全取决于是否包裹在fieldset元素中:
console.log('h2 pseudo without fieldsets:', document.querySelector('.pseudo.no-fieldsets h2').clientHeight+'px');
console.log('legend pseudo without fieldsets:', document.querySelector('.pseudo.no-fieldsets legend').clientHeight+'px');
console.log('h2 pseudo with fieldsets:', document.querySelector('.pseudo.with-fieldsets h2').clientHeight+'px');
console.log('legend pseudo with fieldsets:', document.querySelector('.pseudo.with-fieldsets legend').clientHeight+'px');
console.log('h2 real without fieldsets:', document.querySelector('.real.no-fieldsets h2').clientHeight+'px');
console.log('legend real without fieldsets:', document.querySelector('.real.no-fieldsets legend').clientHeight+'px');
console.log('h2 real with fieldsets:', document.querySelector('.real.with-fieldsets h2').clientHeight+'px');
console.log('legend real with fieldsets:', document.querySelector('.real.with-fieldsets legend').clientHeight+'px');
body * {
background-color: rgba(0,0,0,.1);
}
h2::before,
legend::before {
content: "";
display: block;
height: 150px;
margin-top: -150px;
}
h2, legend {
display: block !important;
height: auto !important;
}
<div class="pseudo no-fieldsets">
<p>pseudo element version without fieldsets</p>
<h2></h2>
<legend></legend>
</div>
<div class="real no-fieldsets">
<p>real element version without fieldsets</p>
<h2>
<div></div>
</h2>
<legend>
<div></div>
</legend>
</div>
<div class="pseudo with-fieldsets">
<p>pseudo element version with fieldsets</p>
<fieldset>
<h2></h2>
</fieldset>
<fieldset>
<legend></legend>
</fieldset>
</div>
<div class="real with-fieldsets">
<p>real element version with fieldsets</p>
<fieldset>
<h2>
<div></div>
</h2>
</fieldset>
<fieldset>
<legend>
<div></div>
</legend>
</fieldset>
</div>
关于html - 图例不包括::之前而 h2 包括,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49307012/