CSS
How to make a child element appear behind its parent in CSS
📣 Sponsor
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:
<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. For our example, this requires adding the following code to the child and parent:
.parent {
transform-style: preserve-3d;
}
.child {
transform: translateZ(-10px)
}
Our final CSS then looks like this:
.parent {
background: linear-gradient(45deg, #ff4ea0, #0043ff);
width: 200px;
height: 200px;
border-radius: 10px;
font-weight: 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-weight: 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 1615228337856
More Tips and Tricks for CSS
- CSS Layers Tutorial: Real CSS Encapsulation
- How the CSS Box Model Works
- Creating a Javascript Drawing and Annotation Application
- CSS Fonts
- Stripe-Like Smooth Transition CSS Only Menu
- How to Make your text look crisp in CSS
- A first look at CSS When and Else Statements
- Creating 3D CSS Buttons which Move as you Mouse Over
- CSS Pixel Art Generator
- A Guide to CSS Selectors