简体   繁体   中英

Absolutely-positioned elements with the same z-index: which element will be on top?

Let's say you have several images in a DIV which are absolutely positioned such that they overlap but with no z-index defined :

CSS

img {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100px;
    height: 100px;
}

HTML

<div>
    <img src="...">
    <img src="...">
    <img src="...">
</div>

I've noticed that Safari and Chrome will display the last element on top. Is this standard behavior? In other words, is it relatively safe to assume that most browsers will display the last element on top?

Yes, it's safe to assume. According to the W3C :

Each box belongs to one stacking context. Each positioned box in a given stacking context has an integer stack level, which is its position on the z-axis relative other stack levels within the same stacking context. Boxes with greater stack levels are always formatted in front of boxes with lower stack levels. Boxes may have negative stack levels. Boxes with the same stack level in a stacking context are stacked back-to-front according to document tree order .

generally, the last activated will be on top.

div a is z-index 10, and appears first in the document

div b is z-index 10, and appears second in the document

when the document renders b will be above a, because a was written, then b written over top.

modifying a could bring it on top.

basically you should have a click handler on 'a' to raise it if you will ever need a to appear on top of b.

The last image in that same position read by the browser will be shown. Yes it's a safe bet that is the case in all browsers, because all files are read line by line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM