Thursday, 21 February 2013

CSS: Layers

   


We can use CSS to overlap elements on a page. We are talking about putting one element on top of another.
To do so we can define the z-index. Something like:
Maecenas vel commodo magna. Aliquam facilisis, erat eu rhoncus elementum, elit eros venenatis risus, vitae tincidunt dui lorem a tellus. Integer non magna a mi euismod ultricies. Aliquam sit amet tortor est. Vivamus sollicitudin neque et justo vestibulum dignissim.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam dictum tincidunt turpis vitae rhoncus. Donec massa enim, fringilla nec vestibulum at, congue hendrerit dolor. Integer rutrum volutpat condimentum. In consequat ornare erat, ac condimentum diam molestie ac. Nullam ligula lacus, posuere vel rhoncus at, ullamcorper eget lacus. Etiam non nisi urna. Vivamus elementum orci sed diam rhoncus vitae pharetra dolor commodo. Vestibulum varius cursus orci nec ullamcorper. Curabitur nulla sapien, laoreet eu convallis ac, luctus in tellus.

It's very simple and the effect can be interesting in many situations.

The way it is done: two divs with different classes (a and b).
<div class="a">
Maecenas vel commodo magna. Aliquam facilisis, erat eu rhoncus elementum, elit eros venenatis risus, vitae tincidunt dui lorem a tellus. Integer non magna a mi euismod ultricies. Aliquam sit amet tortor est. Vivamus sollicitudin neque et justo vestibulum dignissim.
</div>
<div class="b">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam dictum tincidunt turpis vitae rhoncus. Donec massa enim, fringilla nec vestibulum at, congue hendrerit dolor. Integer rutrum volutpat condimentum. In consequat ornare erat, ac condimentum diam molestie ac. Nullam ligula lacus, posuere vel rhoncus at, ullamcorper eget lacus. Etiam non nisi urna. Vivamus elementum orci sed diam rhoncus vitae pharetra dolor commodo. Vestibulum varius cursus orci nec ullamcorper. Curabitur nulla sapien, laoreet eu convallis ac, luctus in tellus.
 </div>
Then we need to style those two divs:
<style>
.a {
position: relative;
top: 30px;
left: 5px;
z-index: 2;
background-color: #330000;
}
.b { 
position: relative;
z-index: 1;
background-color: #FF0000;
}
</style>
The b div will stay on top of the a div because of the z-index.
Basically when we need overlapping elements, the z-index property can be set to determine the order in which elements overlaps. The greater the z-index value the more the element will be placed in front. If no z-index value is set, the last positioned element in the normal html flow will be positioned in front.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.