DEV Community

Leira Sánchez
Leira Sánchez

Posted on

23 7

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay