编程小贴士

给你的编程提供小点子


关于z-index的那些事儿

关于z-index的真正问题是,很少有人理解它到底是怎么用。其实它并不复杂,但是如果你从来没有花一定时间去看具体的z-index相关文档,那么你很可能会忽略一些重要的信息。

不相信我吗?好吧,看看你能否解决下面这个问题:

问题:

在 接下来的HTML里 有三个<div>元素,并且每个<div>里包含一个<span>元素。每 个<span>被分别给定一个背景颜色:红、绿、蓝。每个<span>被放置到文档的左上角附近,部分重叠着其他 的<span>元素,这样你就可以看到哪些是被堆叠在前面。第一个<span>有一个z-index的值为1,而其他两个没有任 何z-index值。

以下就是这个HTML和它的基本CSS。

HTML代码

1
2
3
4
5
6
7
8
9
<div>
  <span>Red</span>
</div>
<div>
  <span>Green</span>
</div>
<div>
  <span>Blue</span>
</div>

CSS代码

1
2
3
4
5
6
7
8
9
10
11
12
13
.red, .green, .blue {
  position: absolute;
}
.red {
  background: red;
  z-index: 1;
}
.green {
  background: green;
}
.blue {
  background: blue;
}

tips1000_2014-10-20_00-16-391

挑战:

尝试使红色<span>元素堆在蓝色和绿色<span>的后面,不要打破以下规则:

    • 不要以任何方式改变HTML标记
    • 不要添加/修改任何元素的z-index属性
    • 不要添加/修改任何元素的position属性

如果你找到了答案,那么它应该像下面这样:

1
2
3
4
5
6
7
8
9
<div>
  <span>Red</span>
</div>
<div>
  <span>Green</span>
</div>
<div>
  <span>Blue</span>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
div:first-child {
  opacity: .99;
}
.red, .green, .blue {
  position: absolute;
}
.red {
  background: red;
  z-index: 1;
}
.green {
  background: green;
}
.blue {
  background: blue;
}

tips1000_2014-10-20_00-16-39

解决方案:

这个解决方法是在第一个<div>里(红色<span>的父节点)添加一个小于1的opacity属性值。下面就是被添加的CSS的例子:

1
2
3
div:first-child {
  opacity: .99;
}

如果你现在很震惊,但是仍然百思不得其解,并且不相信opacity能决定哪个元素堆在前面,欢迎来社区提问,当第一次在这个问题上被困扰时我同样很震惊。

希望接下来的内容能够让你对这个问题更清楚些。

堆栈顺序

Z-index看上去如此简单:高的z-index堆在低的z-index的前面,对吗?这实际上是错的,是z-index问题的一部分。它看上去如此的简单,以至于很多开发者没有花相应的时间去读相关的规则。

每一个在HTML文档中的元素既可以在其他元素的前面,也可以在其他元素的后面。这就是所谓的堆栈顺序。决定这个顺序的规则被十分清楚的定义在说明文档中,但是就像之前我已经提到过,这些文档没有被大多数开发者们完全弄明白。

当z-index和position属性不被包括在内时,这些规则相当简单:基本上,堆栈顺序和元素在HTML中出现的顺序一样。(好吧,其实是有一点复杂的,但是只要你不使用压缩边界来重叠行内元素,你可能不会遇到边界问题。)

当你把位置属性也包括在内介绍时,任何定位元素(和他们的子元素)都在非定位元素前被显示出来。(说一个元素被“定位”意思是它有一个不同于静态的位置值,例如相对的,绝对的,等等。)

最 后,当z-index被提及时,事情变的有点儿复杂。最初,很自然的假设带有高z-index值的元素会在带有低z-index值的元素前面,但是后来发 现没那么简单。首先,z-index只对定位元素起作用。如果你尝试对非定位元素设定一个z-index值,那么肯定不起作用。其次,z-index值能 创建堆栈上下文环境,并且突然发现看似简单的东西变的更加复杂了。

堆栈上下文

一组具有共同双亲的元素,按照堆栈顺序一起向前或向后移动构成了所谓的堆栈上下文。充分理解堆栈上下文是真正掌握z-index和堆栈顺序工作原理的关键。

每 一个堆栈上下文都有一个HTML元素作为它的根元素。当一个新的堆栈上下文在一个元素上形成,那么这个堆栈上下文会限制所有的子元素以堆栈的顺序存储在一 个特别的地方。那意味着一旦一个元素被包含在处于底部堆栈顺序的堆栈上下文中,那么就没有办法先出现于其他处于更高的堆栈顺序的不同堆栈上下文元素,就算 z-index值是十亿也不行!

现在,堆栈上下文有三种方法可以在一个元素上形成:

    • 当一个元素是文档的根元素时(<html>元素)
    • 当一个元素有一个position值而不是static,有一个z-index值而不是auto
    • 当一个元素有一个opacity值小于1

前两种形成堆栈上下文的方法具有很大意义并且被广大Web开发者所理解(即使他们不知道这些被叫做什么)。第三种方法(opacity)几乎从来没在w3c说明文档之外被提及过。

用堆栈顺序决定一个元素的位置

实际上,为一个页面上的所有元素决定全局堆栈顺序(包括边界、背景、文本节点、等等)是极度复杂的,并且远远超越了本文讲述的范围(再一次,参考文 档)。但是我们最大的目的,就是基本了解这个顺序,它能够在很长一段时间内帮助我们提高CSS开发的可预测性。所以,让我们打破顺序,分解为独立的堆栈上 下文。

在同样的堆栈上下文里的堆栈顺序

下面是几条基本的规则,来决定在一个单独的堆栈上下文里的堆栈顺序(从后向前):

    • 堆栈上下文的根元素
    • 定位元素(和他们的子元素)带着负数的z-index值(高的值被堆叠在低值的前面;相同值的元素按照在HTML中出现的顺序堆叠)
    • 非定位元素(按照在HTML中出现的顺序排序)
    • 定位元素(和他们的子元素)带着auto的z-index值(按照在HTML中出现的顺序排序)
    • 定位元素(和他们的子元素)带着正z-index值(高的值被堆叠在低值的前面;相同值的元素按照在HTML中出现的顺序堆叠)

注 解:定位元素带有负的z-index值被在一个堆栈上下文中先排序,这意味着他们出现在所有其他元素的后面。正因如此,它使一个元素出现在自己父元素之后 成为可能,这以前通常是不可能的事。当然,这局限于它的父元素与它在同一个堆栈上下文,并且不是那个堆栈上下文的根元素。一个伟大的例子如Nicolas Gallagher的CSS不用图像降低阴影。

全局堆栈顺序

坚定的理解了为什么/什么时候新的堆栈上下文形成,同时掌握了同一个堆栈上下文的堆栈顺序,现在让你来找出一个特定元素将出现在全局堆栈里的顺序不是那么糟糕了吧?

避免错误的关键是能够发现新的堆栈上下文什么时候形成。如果你对一个元素设置了z-index值为十亿但是它没有在堆栈顺序中向前移动,检查一下它的祖先树,看是否它的父节点形成了堆栈上下文。如果是那样的话,你的z-index值即使有十亿也不会给你带来好处。

包扎救治

回到之前的原始问题,我已经重建了这个HTML的结构,添加了一些注释,每一个标签指明了它在堆栈里的顺序。这个顺序是假设最初的CSS。

1
2
3
4
5
6
7
8
9
<div><!-- 1 -->
  <span><!-- 6 --></span>
</div>
<div><!-- 2 -->
  <span><!-- 4 --><span>
</div>
<div><!-- 3 -->
  <span><!-- 5 --></span>
</div>

当我们添加opacity到第一个<div>,堆栈顺序像下面这样改变:

1
2
3
4
5
6
7
8
9
<div><!-- 1 -->
  <span><!-- 1.1 --></span>
</div>
<div><!-- 2 -->
  <span><!-- 4 --><span>
</div>
<div><!-- 3 -->
  <span><!-- 5 --></span>
</div>

span.red曾经的顺序是6,但现在改为1.1。我已经使用“.”来标注一个新的上下文环境的形成。span.red现在是那个新的上下文的第一个元素。

现 在似乎更清晰了,关于为什么红色盒子跑到其他盒子的后面。原始的例子只包含两个堆栈上下文,根元素和形成span.red的那个。当我们添加 opacity到span.red的父节点上,形成了第三个堆栈上下文,结果显示在span.red上的z-index值只能应用在那个新的堆栈上下文 中。因为第一个<div>(应用opacity的那个)和它的兄弟元素没有position或者z-index值的集合,他们的堆栈顺序是由 他们在HTML里的源顺序决定的,也就是说第一个<div>,和它的堆栈上下文里的所有元素被第二个和第三个<div>元素分 离。

102 Responses to “ 关于z-index的那些事儿 ”

  1. suba suba说道:

    MgzlAn stumbleupon everyday. It as always useful

  2. That as in fact a good movie stated in this post about how to write a piece of writing, therefore i got clear idea from here.

  3. kissmovies说道:

    You made some decent points there. I appeared on the internet for the issue and found most individuals will go along with with your website.

  4. Wow, great article post.Really thank you! Will read on

  5. girl coloring说道:

    Thank you for your blog.Much thanks again. Much obliged.

  6. It looks to me that this web site doesnt load up in a Motorola Droid. Are other folks getting the same problem? I enjoy this web site and dont want to have to miss it when Im gone from my computer.

  7. Muchos Gracias for your post.Much thanks again. Keep writing.

  8. There may be noticeably a bundle to learn about this. I assume you made sure good factors in options also.

  9. trying to in finding issues to improve my website!I guess its ok

  10. Thanks for the blog.Much thanks again. Cool.

  11. sure, analysis is paying off. Seriously handy perspective, many thanks for sharing.. Truly handy point of view, many thanks for expression.. Fantastic beliefs you have here..

  12. Click to read说道:

    They are really convincing and can definitely work.

  13. Major thanks for the blog article.Thanks Again. Want more.

  14. check my blog说道:

    There as certainly a great deal to learn about this issue. I love all of the points you have made.

  15. omlet arcade说道:

    You made some decent points there. I looked on the internet for the issue and found most individuals will agree with your site.

  16. webpage说道:

    Nice post, thanks. Could you explain the third paragraph in more detail?

  17. It as best to take part in a contest for one of the best blogs on the web. I will recommend this web site!

  18. I truly appreciate this post. I ave been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thx again!

  19. It is in reality a nice and useful piece of info. I am satisfied that you shared this helpful tidbit with us. Please keep us informed like this. Thank you for sharing.

  20. party Poker.com view of Three Gorges | Wonder Travel Blog

  21. There is noticeably a bunch to know about this. I consider you made various nice points in features also.

  22. Woking taxi说道:

    You got a very good website, Glad I observed it through yahoo.

  23. Many thanks for sharing this first-class post. Very interesting ideas! (as always, btw)

  24. Thanks for sharing, this is a fantastic article.Really thank you! Much obliged.

  25. view说道:

    tee shirt guess ??????30????????????????5??????????????? | ????????

  26. your blog. It appears as though some of the text within your posts are running off the screen.

  27. you have an amazing blog here! would you prefer to make some invite posts on my weblog?

  28. PhD Green Card说道:

    We stumbled over here by a different website and thought I might as well check things out.

  29. Nwokolo Collins说道:

    Wow, incredible blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is fantastic, let alone the content!

  30. ma giam gia tiki说道:

    There is apparently a bundle to know about this. I suppose you made certain good points in features also.

  31. trang tri noel说道:

    Say, you got a nice blog article.Thanks Again. Really Great.

  32. What as up, I read your blogs like every week. Your humoristic style is witty, keep up the good work!

  33. Really appreciate you sharing this blog post. Much obliged.

  34. Wow! Thank you! I constantly wanted to write on my site something like that. Can I implement a portion of your post to my site?

  35. The best and clear News and why it means a great deal.

  36. hip hop说道:

    Wow, great article post.Really looking forward to read more. Much obliged.

  37. There is perceptibly a lot to identify about this. I consider you made some good points in features also.

  38. Really informative post.Really looking forward to read more. Keep writing.

  39. Major thankies for the blog article.Much thanks again. Really Great.

  40. Say, you got a nice blog article.Much thanks again. Want more.

  41. incredibly nice post, i certainly love this website, persist in it

  42. It as really a great and useful piece of information. I am glad that you shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.

  43. Wow! Thank you! I always wanted to write on my site something like that. Can I include a fragment of your post to my website?

  44. viagra without prescription! Overnight shiping! Click here now and get discount!

  45. You made some good points there. I checked on the internet to learn more about the issue and found most people will go along with your views on this website.

  46. Supermodel Elena说道:

    Very very good publish, thank that you simply lot regarding sharing. Do you happen a great RSS feed I can subscribe to be able to?

  47. url shortener说道:

    It as hard to find experienced people on this topic, however, you sound like you know what you are talking about! Thanks

  48. fitness说道:

    There is noticeably a lot to identify about this. I believe you made various nice points in features also.

  49. visit this site说道:

    we came across a cool website which you could appreciate. Take a look for those who want

  50. It as not that I want to duplicate your web-site, but I really like the pattern. Could you tell me which style are you using? Or was it especially designed?

  51. too substantially vitamin-a may also lead to osteoporosis but aging could be the quantity cause of it`

  52. Como tejer说道:

    I’а†ve read a few excellent stuff here. Definitely price bookmarking for revisiting. I surprise how so much effort you place to make this kind of magnificent informative web site.

  53. Really appreciate you sharing this article.Really looking forward to read more. Want more.

  54. you have an excellent weblog right here! would you like to make some invite posts on my weblog?

  55. my page说道:

    Nice post. I learn something new and challenging on websites I stumbleupon everyday. It will always be useful to read content from other authors and practice a little something from other sites.

  56. worth说道:

    I truly appreciate this article.Really thank you!

  57. Thanks for sharing, this is a fantastic blog.Much thanks again. Really Cool.

  58. School news说道:

    Keep up the superb piece of work, I read few articles on this web site and I think that your web blog is very interesting and has got sets of great info.

  59. School admission说道:

    Looking forward to reading more. Great blog post.Thanks Again. Awesome.

  60. Just read this I was reading through some of your posts on this site and I think this internet site is rattling informative ! Keep on posting.

  61. You made some nice points there. I looked on the internet for the subject and found most people will consent with your website.

  62. Open heavens说道:

    Very good post! We are linking to this great post on our website. Keep up the good writing.

  63. This is a topic which is near to my heart Thank you! Where are your contact details though?

  64. Tumblr article You are a very intelligent person!

  65. scary maze说道:

    Im thankful for the article.Really thank you! Cool.

  66. This really solved my problem, thank you!

  67. state. This is the first time I frequented your web page and up to now?

  68. share说道:

    Perfectly pent written content, appreciate it for entropy. The earth was made round so we would not see too far down the road. by Karen Blixen.

  69. In my opinion you commit an error. Let as discuss. Write to me in PM, we will communicate.

  70. Thanks for sharing this good post. Very inspiring! (as always, btw)

  71. happy wheels 6说道:

    This blog is without a doubt educating and besides amusing. I have found a bunch of handy stuff out of this source. I ad love to come back again soon. Thanks a lot!

  72. Really appreciate you sharing this post.Really thank you! Want more.

  73. Wow! This could be one particular of the most useful blogs We have ever arrive across on this subject. Actually Excellent. I am also an expert in this topic so I can understand your effort.

  74. Thanks again for the blog article.Much thanks again. Keep writing.

  75. Your style is so unique in comparison to other people I ave read stuff from. Many thanks for posting when you ave got the opportunity, Guess I will just bookmark this web site.

  76. You ought to be a part of a contest for one of the best sites on the net.

  77. devotionals说道:

    Red your weblog post and beloved it. Have you at any time imagined about visitor posting on other related blogs related to your site?

  78. official site说道:

    It as really a great and useful piece of information. I am glad that you shared this helpful info with us. Please keep us informed like this. Thank you for sharing.

  79. go to说道:

    Nice post. I learn something new and challenging on websites I stumbleupon everyday. It will always be useful to read content from other authors and practice something from their websites.

  80. for more info说道:

    Thank you for your article post.Really looking forward to read more. Fantastic.

  81. you can check说道:

    Muchos Gracias for your blog article.Thanks Again. Keep writing.

  82. Just a smiling visitor here to share the love (:, btw great pattern.

  83. Premio Yo Emprendo.com Anglica Mara Moncada Muoz

  84. Some genuinely superb content on this site, regards for contribution.

  85. facebook说道:

    of things from it about blogging. thanks.

  86. for more details说道:

    I visit every day a few sites and information sites to read articles or reviews, however this webpage provides feature based writing.

  87. indeed, research is paying off. Great thoughts you possess here.. Particularly advantageous viewpoint, many thanks for blogging.. Good opinions you have here..

  88. garage door说道:

    Way cool! Some extremely valid points! I appreciate you penning this write-up plus the rest of the site is also really good.

  89. click here说道:

    very nice submit, i definitely love this web site, carry on it

  90. Just Browsing While I was surfing yesterday I noticed a great post about

  91. Find out more说道:

    This blog is definitely entertaining and factual. I have picked up a bunch of interesting advices out of this blog. I ad love to come back again and again. Thanks a bunch!

  92. caratulas CD说道:

    I truly apprwciatwd your own podt articlw.

  93. ballinaadvocate说道:

    There is clearly a bundle to realize about this. I assume you made certain nice points in features also.

  94. Shaunte Lalande说道:

    The information you have was perfect that we’re seeking and i also really enjoyed the content. I would like to visit your site again from now on.

  95. buy说道:

    Really enjoyed this blog post.Much thanks again. Awesome.

  96. I simply could not depart your site before suggesting that I actually enjoyed the standard info a person provide on your guests? Is gonna be back incessantly in order to check up on new posts.

  97. Really cool post, highly informative and professionally written..Good Job! car donation sites

  98. Nice blog right here! Also your website lots up very fast! What web host are you using? Can I am getting your affiliate hyperlink to your host? I wish my web site loaded up as fast as yours lol

  99. Magnificent site. A lot of useful info here.

  100. Well I sincerely enjoyed studying it. This tip procured by you is very constructive for accurate planning.

  101. check here说道:

    Thanks again for the blog post.Really thank you! Awesome.

  102. Well I definitely liked reading it. This information offered by you is very constructive for proper planning.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>