普通元素的层次问题

对定位元素使用z-index属性可以直接对元素设置层次,它会在渲染时影响元素的遮盖顺序。但z-index属性仅对定位元素生效,那么对于非定位元素呢?实际上在非定位元素之间也有自己的层次设置方案,一些普通的属性就可以影响非定位元素的遮盖顺序。
  通常,在文档中位置较后的元素会挡住较前的元素。
运行<style>
div {width:16px;height:16px;margin-right:-10px;margin-bottom:-10px;}
</style>
<div style="background:red;"></div>
<div style="background:green;"></div>
<div style="background:blue;"></div>

  但块级元素无法挡住浮动的元素,而浮动的元素又无法挡住行级元素。
运行<style>
div {width:16px;height:16px;margin-right:-10px;margin-bottom:-10px;}
</style>
<div style="background:red;display:inline-block;"></div>
<div style="background:green;float:left;"></div>
<div style="background:blue;"></div>

  也就是说,非定位元素的层次关系是:块级元素 < 浮动元素 < 行级元素
  另外,对于定位元素的层次,要看z-index的设置。如果z-index不为负则比非定位元素的层次高(会挡住非定位元素),如果为负则层次低(会被挡住)。运行<style>
div {width:16px;height:16px;margin-right:-10px;margin-bottom:-10px;}
</style>
<div style="background:red;display:inline-block;"></div>
<div style="background:green;float:left;"></div>
<div style="background:blue;"></div>
<div style="background:yellow;position:relative;z-index:-1;"></div>
<div style="
  background:cyan;left:10px;top:-10px;
  position:relative;
  /*默认z-index为auto,与父元素相等(等于0,是非负数)*/
"></div>

posted @ 2014-08-07 15:07  axl234  阅读(382)  评论(0编辑  收藏  举报