概述
visibility:hidden: The generated box is invisible (fully transparent, nothing is drawn), but still affects layout. Furthermore, descendants of the element will be visible if they have 'visibility: visible'.
当 visibility:hidden 时,生成的盒子将不可见,但是仍然影响布局,并且,如果后代元素设置 visibility: visible ,那么他们依然是可见的。
display:none: This value causes an element to not appear in the formatting structure (i.e., in visual media the element generates no boxes and has no effect on layout). Descendant elements do not generate any boxes either; the element and its content are removed from the formatting structure entirely. This behavior cannot be overridden by setting the 'display' property on the descendants.
Please note that a display of 'none' does not create an invisible box; it creates no box at all. CSS includes mechanisms that enable an element to generate boxes in the formatting structure that affect formatting but are not visible themselves. Please consult the section on visibility for details.
当 display:none 时,元素将不会出现在“formatting structure”(这里的 formatting structure 可以理解为视觉上的 DOM 树)中。同时后代元素也不会生成盒子,该元素和他的内容见完全从“formatting structure”中移除,同时设置后代的 display 属性不会覆盖这个行为。
display:none 不会生成任何盒子,所以元素设置 display:none 后不会影响布局。
详解
区别一、visibility:hidden 元素不可见但仍然占用空间,影响布局;display:none 元素不可见且不占用空间,不影响布局
<div>
<strong>给元素设置display:none样式</strong>
<p>A元素</p>
<p style='display:none;'>B元素</p>
<p>C元素</p>
</div>
<div>
<strong>给元素设置visibility:hidden样式</strong>
<p>A元素</p>
<p style='visibility:hidden;'>B元素</p>
<p>C元素</p>
</div>
区别二、visibility:hidden 元素的子元素会继承 visibility:hidden 但是可以覆盖该设置,如果子元素设置 visibility:visible 则子元素可见;display:none 元素的子元素会继承 display:none 且不可覆盖,因此 display:none 元素内的所有元素都不再可见。
区别三、visibility: hidden 不会影响计数器的计数,display: none 则会影响计数器计数。
<div>
<strong>给元素设置visibility:hidden样式</strong>
<ol>
<li>元素1</li>
<li style="visibility:hidden;">元素2</li>
<li>元素3</li>
<li>元素4</li>
</ol>
</div>
<div>
<strong>给元素设置display:none样式</strong>
<ol>
<li>元素1</li>
<li style="display:none;">元素2</li>
<li>元素3</li>
<li>元素4</li>
</ol>
</div>
区别四、CSS3 的 transition 支持 visibility 属性,但是并不支持 display 属性。