Stacking Elements in CSS


You can stack the HTML elements using CSS property z-index. Z-Index allow to order the element in the stack of HTML Elements. This is useful when you want to show HTML Element over other Elements. For Example, you want to bring the motorbike on the front.

Z-Index in CSS2

index.html

<img id="image1" src="https://www.vintagetoysillustrated.com/2014/vintage-toys-for-sale/february/MASUDAYA_MODERN_TOYS_BATTERY_OPERATED_TIN_ATOM_MOTORCYCLE_MADE_IN_JAPAN_LEFT_SIDE.JPG" />

<img id="image2" src="https://c1.staticflickr.com/9/8275/8711350465_325712353c_z.jpg" />
style.css

img{
    width:320px;
}
#image1{
    position:absolute;
    top:0;
    left:0;
}
#image2{
    position:absolute;
    top:83px;
    left:50px;
}

You see I don’t use the z-index property yet. And the car image is displayed on the front of motorbike image. This is because,

If two positioned elements overlap without a z-index specified, the element positioned last in the HTML code will be shown on top. -w3Schools

For Example, you now want to bring the motorbike image on the front. What would you do change the HTML coding. Write the motorbike image tag after the car image tag. This is one solution. But, the better solution is to use CSS z-index property to order the HTML Elements in the stack the way you want. So, apply the z-index property to #image1 (bike image) and sets it value higher than the #image2. If the #image2 has no z-index property set. It mean that is z-index value is zero. So, set z-index value to 1 for #image1.

style.css

#image1{
    position:absolute;
    top:0;
    left:0;
    z-index:1;
}

Z-Index in CSS-2

The higher the z-index value, the more it appear on the front.

May be the above text is grammatically wrong. 😉. Anyway see the demo on JsFiddle

Advertisements

One thought on “Stacking Elements in CSS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s