CSS

How to make a child element appear behind its parent in CSS

A common situation in the past was that you had an element within another, which you wanted to appear behind the parent element. For example:

html Copy
<div class="parent"> I am the parent <div class="child"> I am the child, but I want to be behind my parent </div> </div>

Will by default produce a result like this:

I am the parent
I am the child, but I want to be behind my parent

To get this to work, you would have to remove the child from the parent, something which is not always possible. With modern CSS, you can resolve this issue by translating the element along the Z axis. This requires adding the following code to the child and parent:

css Copy
.parent { transform-style: preserve-3d; } .child { transform: translateZ(-10px) }

Preserving the 3D nature of our parent ensures the whole object is treated as a 3D object. Then we can move our child along the Z-axis to a position behind the parent. Our final CSS then looks like this:

css Copy
.parent { background: linear-gradient(45deg, #ff4ea0, #0043ff); width: 200px; height: 200px; border-radius: 10px; font-variation-settings: 'wght' 700; padding: 1rem; box-shadow: 0 2px 30px rgb(0 0 0 / 50%); margin-bottom: 4rem; transform-style: preserve-3d; } .child { background: linear-gradient(45deg, #4effef, #0014ff); width: 200px; font-variation-settings: 'wght' 700; height: 200px; border-radius: 10px; position: relative; top: 30px; left: 30px; padding: 1rem; box-shadow: 0 2px 30px rgb(0 0 0 / 50%), 0 0 0 1px rgba(0,0,0,0.05); transform: translateZ(-10px) }

Which results in the child now appearing behind the parent:

I am the parent
I am the child, but I want to be behind my parent
Last Updated Monday, 8 March 2021
Click to Subscribe Subscribed

Subscribe

Subscribe to stay up to date with our latest posts via email. You can opt out at any time.

Not a valid email