CSS – z-index

介绍

z-index 是用来设置 element 层次高低的 (当 element 重叠的时候)

 

参考:

4 reasons your z-index isn’t working (and how to fix it)

深入理解 CSS 属性 z-index

Z-index CSS Tutorial ( Position and Stacking Order )

 

Element 重叠时默认表现

先了解一下在没有做任何 z-index 时, CSS 默认的规则

假设有 2 个 div

  <body>
    <div class="div1">div1</div>
    <div class="div2">div2</div>
  </body>

div2 有 margin-top: -20px, 所以它们重叠了

.div1 {
  width: 100px;
  height: 100px;
  background-color: red;
}
.div2 {
  width: 100px;
  height: 100px;
  background-color: yellow;

  margin-top: -20px;
}

效果

CSS – z-index

 div2 覆盖到了 div1 上面. 这是因为在没有任何 z-index 干预的情况下, HTML element 结构顺序, 越下方就越上层 (后来居上的原则)

 

漂浮元素

同一个例子, 如果让 div1 浮起来, position: relative

.div1 {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
}

那么它就跑到上面了.

CSS – z-index

这是 CSS 默认的第 2 规则. 漂浮着比较高. 不只是 position: relation 会漂浮哦. 

transform: translateZ(0); 也可以让它漂起来, 这是 Safari 常见的优化写法 (很多人 set 了之后就发现层次不对了, 就是这个原因).

 

z-index

首先, z-index 只适用于 positioned element (或者说漂浮物)

z-index 越大就越上层. default value 是 auto. 

0 是一般 level, 1 或以上就表示想在上层, -1 通常是用来表示要比一般的 0 (没有设置的元素) 低层.

上面的例子, 当 div1,2 都是 relative 后, 如果想让 div1 在上层, 可以 set z-index: 1, 或者把 div2 set 成 z-index: -1.

.div1 {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  z-index: 1;
}
.div2 {
  width: 100px;
  height: 100px;
  background-color: yellow;

  margin-top: -20px;
  position: relative;
  /* z-index: -1; */
}

 

Parent Limit Child z-index

child z-index 是会被 parent z-index 限制的. 

比如 parent z-index: 0. child z-index: 100, 这个 100 只在 parent 内管用, 到了外面其余 element 1 也比它搞 (因为 parant 是 0)

注: parent 如果完全没有 set z-index 那么就没有 limit.

这里给一个很常见的例子:

有个 section, 有大背景图, 上面有一个 call to action button

然后想加一层黑影到图片上去. 但是 call to action button 要保持可以被点击.

HTML 结构

  <body>
    <div class="container">
      <button class="button">call to action</button>
      <div class="overlay"></div>
    </div>
  </body>

CSS

.container {
  width: 300px;
  height: 300px;
  background-image: url(img/hero-bg.png);
  position: relative;
}

.button {
  padding: 10px;
}

.overlay {
  background-color: black;
  opacity: 0.7;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

overlay 是 absolute 定位, 对准其 parent relative. 这样就把整个 parent 覆盖完了. 也包括了 parent 里面的 button

button 和 overlay 是 sibling. overlay 漂浮, 所以在 button 上层. button 就被挡住了.

要让 button 上来, 要嘛让它漂浮配上 z-index, 要不然就是让 overlay 往下沉.

overlay z-index: -1 就可以让它低于 button 了.

添加 -1 后很惊讶的发现, overlay 不见了. 原因是 -1 会让它比 parent 还低. 所以它跑到 parent background-image 的后面了.

CSS – z-index

上面有提到, parent 可以 limit z-index, 由于目前 parent 没有 set 任何 z-index, 所以 overlay -1 是可以越过 parent 的.

在 parent 设置 z-index: 0, 其实 set 什么都可以只要不是 auto (auto = 没有 set). 

set 100 或 -100 效果都是一样的, 因为关键是它阻止了 child 出去, 没有出去也就不可能会比 parent 低了. 所以建议设置 0

CSS – z-index

 

 

 

上一篇:第二次网页前端培训笔记(HTML P4-P7)


下一篇:Redis事务05