Home > Web Front-end > CSS Tutorial > How to Place a Child Element Behind Its Parent Without Using Z-index?

How to Place a Child Element Behind Its Parent Without Using Z-index?

Patricia Arquette
Release: 2024-11-25 09:45:32
Original
717 people have browsed it

How to Place a Child Element Behind Its Parent Without Using Z-index?

How to Position Child Element Behind Parent without Z-Index

The Question

In some scenarios, you may need a child element to appear below (or behind) its parent, regardless of their position in the DOM tree. However, setting z-index and position: relative doesn't seem to achieve this effect.

The Solution

Thanks to advancements in CSS, you can now accomplish this using CSS 3D transforms. Here's how:


  background: red;<br>  width: 100px;<br>  height: 100px;<br>  transform-style: preserve-3d;<br>  position: relative;<br>}</p><p>.child {<br>  background: blue;<br>  width: 100px;<br>  height: 100px;<br>  position: absolute;<br>  top: -5px;<br>  left: -5px;<br>  transform: translateZ(-10px)<br>}

  Parent<br>  <div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">Child
Copy after login


In this example:

  1. The parent div has the transform-style: preserve-3d property, which enables 3D transforms for the element and its children.
  2. The child div is positioned absolutely within the parent.
  3. The transform: translateZ(-10px) property on the child moves it 10 pixels backward along the z-axis.

As a result, the child element will appear behind the parent, overlaying it without obscuring its view. This technique works in all modern browsers.

The above is the detailed content of How to Place a Child Element Behind Its Parent Without Using Z-index?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template