z-index image

HOW TO CONTROL THE Z-AXIS USING Z-INDEX

Controlling the z-axis of a content using z-index could sometime be as tricky as adding an external styling to your web page(you can have the file but you need to properly link it using the path), for z-index, by default all the content are set to a z-index of zero, and that is why,when you have two or more contents in a container that are positioned absolute, you noticed that the third last or content is closer to you than the other ones. One thing to bear in mind when using this property is that it does not work with position static which is the default position value for almost all elements in our documents.

BEFORE USING Z-INDEX

  • ensure you change the default position value(static) of the element or content.
  • use position relative for the parent container if you want to sit the elements within the parent container.

Now let us check out some codes on how this works.

Supposing, we have our html as

    <body>

    <div>

      <img src=”./Chrysanthemum.jpg” class=”one” alt=”” />

      <img src=”./Desert.jpg” class=”two” alt=”” />

      <img src=”./Penguins.jpg” class=”three” alt=”” />

    </div>

  </body>

Css

div {

  width: 80vw;

  height: 60vh;

  border: 2px solid red;

  padding-left: 50px;

  position: relative;

}

img {

  width: 100px;

  height: 100px;

}

By default, this is what you will have if the position value of the image is static

default result without position value changed

Like I earlier said, Z-index does not work with position static which is the default position value of most elements. And so,we first need to set the parent container to relative and next we need to change the positon value of our images to absolute since we want them to sit within the parent container.

.one {

  position: absolute;

 z-index:0

}            

.two {

  position: absolute;

  top: 5%;

  left: 15%;

z-index:0

}

.three {

  position: absolute;

  top: 10%;

  left: 20%;

z-index:0

}

If you added your CSS properly and your image is well linked, you should have the third image closer to you as seen below

z-index

But for you to control the z-axis, you can change the default value from zero and assign the highest value to the content you want to see closer to you

div {

  width: 80vh;

  height: 60vh;

  padding-left: 50px;

  position: relative;

}

img {

  width: 100px;

  height: 100px;

}

.one {

  position: absolute;

  z-index: 1;

}

.two {

  position: absolute;

  top: 5%;

  left: 15%;

  z-index: 0;

}

.three {

  position: absolute;

  top: 10%;

  left: 20%;

  z-index: -1;

}

z-index result

You should have your first image closer to you by adding the css codes above

And hopefully this gives you a general idea on how to control the z-axis.

Leave a Comment

Your email address will not be published. Required fields are marked *