日志
z-index不起作用的大坑
2019-05-21 09:00
今天遇到的就是z-index不起作用的问题。一个后台小哥不知道抽什么疯,写元素覆盖偏不让用absolute,搞的我之后废了9牛二虎之力写了一下,问题描述是这样的,
一对兄弟节点,insert和parent,parent有两个子节点subtop和subbottom,展现的结果是想让subtop在insert上面,subbottom在insert下面, 代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> .insert{ position: relative; z-index:100; background: green; width:300px; height:300px; top:100px; } .parent{ /*position:relative; z-index: 1000;*/ width:200px; height:200px; /*left:0; top:-50px;*/ border:1px solid #eee; } .subbottom{ position:relative; z-index: 50; width:200px; height:200px; background: red; top:-100px; left:0; } .subtop{ position: relative; z-index:1100; width:100px; height:100px; left:0; top:0; background: blue; } </style> </head> <body> <div class="insert"></div> <div class="parent"> <div class="subtop"></div> <div class="subbottom"></div> </div> </body> </html> 其实原理也很简单,就是利用了z-index的覆盖问题,在写的过程中我发现无论怎么改变,insert的z-index总是无效的,于是百度了一下z-index无效的情况,一共有三种: 1、父标签 position属性为relative; 2、问题标签无position属性(不包括static); 3、问题标签含有浮动(float)属性。 这样也很好理解为什么parent设置了position和z-index之后insert的z-index就会失效的问题了,他的解决办法有是三个: 1、position:relative改为position:absolute; 2、浮动元素添加position属性(如relative,absolute等); 3、去除浮动。 所以,去掉parent的position和z-index,达到了我想要的效果,如下图所示: 蓝蓝设计( www.lanlanwork.com )是一家专注而深入的界面设计公司,为期望卓越的国内外企业提供卓越的UI界面设计、BS界面设计 、 cs界面设计 、 ipad界面设计 、 包装设计 、 图标定制 、 用户体验 、交互设计、网站建设 、平面设计服务。 阅读全文 |