Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 893
David Jones Avatar asked Oct 02 '12 17:10

David Jones


People also ask

What happens if two elements have the same z-index?

Ordering — If two elements have the same z-index, their order in HTML determines which element is placed in front of the other one.

Which Z-index is on top?

The maximum range is ±2147483647. In CSS code bases, you'll often see z-index values of 999, 9999 or 99999.

How do you do absolute positioning with Z-index?

Definition and Usage An element with greater stack order is always in front of an element with a lower stack order. Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).

Is higher z-index on top?

The z-index property determines the stack level of an HTML element. The “stack level” refers to the element's position on the Z axis (as opposed to the X axis or Y axis). A higher value means the element will be closer to the top of the stacking order.


1 Answers

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.

like image 54
j08691 Avatar answered Jan 01 '23 22:01

j08691