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
- iOS Crystalline Blurred Backgrounds with CSS Backdrop Filters
- CSS Inset Borders at Varying Depths
- How to make a child element appear behind its parent in CSS
- Creating Custom, Interactive CSS Checkboxes
- CSS States
- How to Animate SVG paths with CSS
- CSS Positioning
- The Quick Guide to Dark Mode
- An Interactive Guide to CSS Flex Box
- How to make a div the same height as the browser window