传说不包括::之前h2的确如此

时间:2018-03-15 18:43:28

标签: html css html5 css3

为什么legend元素在您clientHeight内容时::before不会更改h2,而height: auto; display: 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>
LANG=en_US.utf8
{{1}}

1 个答案:

答案 0 :(得分:1)

问题实际上与伪元素无关,而是与您的图例位于"damn near impossible to style"字段集中的事实有关。

您可以尝试与字段集及其关联的图例元素的浏览器样式(如果要尝试,我上面链接的文章是相当不错的参考),也可以从HTML中删除字段集(如文章提到,即使字段集是对表单字段集进行分组的最语义方式,但许多人还是避免使用它们),或者您可以在字段集内使用图例元素之外的其他元素。

这里是一个片段,说明了伪元素vs实元素以及带有字段集和没有字段集的情况。如您所见,图例的高度是否为伪元素都为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>