z-index不适用于固定元素 [英] z-index not working for fixed element

查看:100
本文介绍了z-index不适用于固定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



z-index

我正在处理我的代码。 >不适用于固定元素,因此,固定元素总是在前面。



有没有办法将非固定元素在一个固定的元素前面?



谢谢。


$ b

  #fixed {background-color:red;宽度:500px;身高:500px;位置:固定; z-index:0;}#normal {background-color:blue;宽度:500px;身高:500px; z-index:1;}  

< div id = '固定' >我已修正< / div>< div id ='normal'>我正常< / div>

解决方案

除非处理flex项目或grid项目,否则必须为 z-index 定位一个元素才能工作。 1 位置属性的值必须不是静态值 / code>或 z-index 将被忽略。

你的第二个div没有定位。以下是两种选择:


  • 添加位置:相对 #normal

  • 给定位div一个负值 z-index



#fixed {background-color:red;宽度:500px;身高:500px;位置:固定; z-index:0; / *这里的负值也会起作用* /}#normal {background-color:lightblue;宽度:500px;身高:500px; z-index:1;位置:相对; / * new * /}

< div id ='固定'>我已修正< / div>< div id ='normal'>我是普通的< / div>



a CSS的基础知识 z-index 属性






1 虽然 z-index CSS 2.1 中的定义,c>仅适用于CSS 3允许 z-index 使用网格项目弹性项目即使 position 是 static



2 z-index MDN属性页面


I was working on my code when I stumbled upon this fun fact:

z-index doesn't work for a fixed element and, therefore, fixed elements will always be in front.

Is there a way to place a non-fixed element in front of a fixed element?

Thanks.

#fixed {
  background-color: red;
  width: 500px;
  height: 500px;
  position: fixed;
  z-index: 0;
}
#normal {
  background-color: blue;
  width: 500px;
  height: 500px;
  z-index: 1;
}

<div id = 'fixed'> I'm Fixed </div>
<div id = 'normal'> I'm Normal </div>

解决方案

Unless you're dealing with flex items or grid items, an element must be positioned for z-index to work.1

In other words, the position property must have a value other than static or z-index will be ignored.2

Your second div is not positioned. Here are two options:

  • add position: relative to #normal, or
  • give the positioned div a negative z-index value

#fixed {
    background-color: red;
    width: 500px;
    height: 500px;
    position: fixed;
    z-index: 0;                   /* a negative value here will also work */
}
#normal {
    background-color: lightblue;      
    width: 500px;
    height: 500px;
    z-index: 1;
    position: relative;           /* new */
}

<div id = 'fixed'> I'm Fixed </div>
<div id = 'normal'> I'm Normal </div>

See also: Basics of the CSS z-index property


1 Although z-index, as defined in CSS 2.1, applies only to positioned elements, CSS 3 allows z-index to work with grid items and flex items, even when position is static.

2 z-index property page at MDN

这篇关于z-index不适用于固定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆