How do you overlay elements with CSS?
The z-index property is used to position elements one above the other and it’s really simple to do!
One of the most common problems when working with different visual elements can be the superposition of these. Luckily the solution to these problems is very simple. There is a CSS property called z-index that allows us to handle the elements as if they were layers, allowing us to decide which element will appear above another.
At first this is difficult to understand since we usually see the web in 2 dimensions and we represent it with width and height, but there is also a third aspect which is the depth. This is what the z-index property allows us to control.
The way it works is simple and to explain it we are going to use the following example. We have 2 boxes, one red and one blue, and one is on top of the other but we can modify it.
Example:
HTML
<div class=”blue”></div>
<div class=”red”></div>
CSS
div {
width:200px;
height:200px;
position:absolute;
}
.blue {
background:blue;
z-index:1; /*The z-index of the blue box is lower than that of the red box*/
}
.red {
background:red;
z-index:2;/*The z-index of the red box is greater than that of the blue box so it is shown after the blue box*/
left:100px;
top:100px;
}
Result looks like this:
Click here to go to Codepen live example
As you can see in the code it is really easy, just add the z-index property to the elements that have conflict. The value that we will put depends on the depth that we want and the element with the highest z-index will be the one that is shown in front. We can use any value, from 1 to whatever we want.
You can see in the example above how the red box is shown in front because it has a higher z-index than the blue box.
Finally, I would like to highlight one thing; the values that the z-index property receives are only integers (whole numbers), so we do not have to add some measure such as px, em, etc. Only integer numbers.
So there you have it! I hope you have found this short tip useful. Feel free to reach out to us if you have any other web related questions.
Graphem Solutions is an award winning web design and development company. If you’re having trouble coming up with a strategy for your website and want to generate and convert more leads contact us. Take advantage of our FREE website analysis and 20 minute consultation. Talk to one of our web experts and get real advice on how to make your website work for you.