DEV Community

Leira Sánchez
Leira Sánchez

Posted on

CSS: Overlay Text Over Image

Alt Text

This example is from the mobile version of a personal website I'm building with HTML/CSS and vanilla JavaScript.

To overlay an element over another, we first need to understand z-index.

Z-Index

z-index is a CSS property that sets the order of elements in a stack.

  • Only works on elements with positions other than static (the default position). They could be absolute, relative, fixed, or sticky.

Let's say your computer's screen is the back, the real world is the front, and every element on your app without a specified z-index is the default layer. If you want to throw something to the back, the z-index will be smaller than 0. The element with the smallest number will go furthest back. If you want to put an element over the default layer, then you use positive numbers. The bigger the number, the closer to the front it will be.

  • Elements are overlayed in ascending order.

  • The default layer is equal to z-index: 0.

  • Negative values of z-index throw elements behind the default layer.

  • The element with the smallest z-index value will be all the way to the back.

  • Positive values throw elements on top of the default layer.

  • The element with the biggest number will be all the way to the front.

Example

Alt Text

Here, I sent the image to the back by setting the z-index to -1. I didn't have to specify a z-index value to my text because it is by default on layer 0, which is above layer -1.

See it on codepen! Disclaimer: I did not make this codepen responsive so it only looks good on desktop.

Playground

Here's a playground on codepen or repl.it for you to experiment with.

Top comments (3)

Collapse
 
haraldson profile image
Hein Haraldson Berg

While understanding z-index is useful in order to understand stacking, I wouldn’t use the z-index CSS property here. Implicit DOM order z-index (later == over) and positioning is all you need to achieve this effect.

Collapse
 
brettanda profile image
Brett Anda 🔥🧠

What are you using to display your code examples like that?

Collapse
 
leirasanchez profile image
Leira Sánchez