Home  >  Article  >  Web Front-end  >  一段代码弄清楚CSS属性display和visibility的差别_html/css_WEB-ITnose

一段代码弄清楚CSS属性display和visibility的差别_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:50:001092browse

CSS如果想要将DOM元素隐藏,有2种做法:将display属性设置成none,或者将visibility属性设置成hidden。下面的html代码没有设置display和visibility属性。

<div id="outA" style="width:400px; height:400px; background:#CDC9C9;position:relative;">	<div id="outB" style="height:200; background:#0000ff;top:100px;position:relative;">	</div>	<div id="outC" style="height:100px; background:#FFB90F;top:50px;position:relative;">	</div></div>


使用display:none隐藏outB

<div id="outA" style="width:400px; height:400px; background:#CDC9C9;position:relative;">	<div id="outB" style="height:200; background:#0000ff;top:100px;position:relative;display:none;">	</div>	<div id="outC" style="height:100px; background:#FFB90F;top:50px;position:relative;">	</div></div>

 

使用visibility:hidden隐藏outB

<div id="outA" style="width:400px; height:400px; background:#CDC9C9;position:relative;">	<div id="outB" style="height:200; background:#0000ff;top:100px;position:relative;visibility:hidden;">	</div>	<div id="outC" style="height:100px; background:#FFB90F;top:50px;position:relative;">	</div></div>

 

对比结果可以很容易得出结论:display:none,元素实际上就从页面中移走了,它后面的元素就会自动上移;而visibility:hidden,则仅仅隐藏该元素,它占据的页面空间依然存在。

 

对于outB元素,如果将display和visibility组合使用会是什么结果呢?

display:block;visibility:hidden;   outB看不见,但仍然占页面空间。

display:none;visibility:hidden;   outB看不见,也不占页面空间。

display:none;visibility:visible;    outB看不见,也不占有空间。

display:block;visibility:visible;    outB可见,肯定占有空间。

上面的测试结果,在IE11/FF17/Chrome39下表现都是一致的。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn