• 0

Can you create a child element with a higher z-index than its parent?


Question

Here's the problem in the form of a fancy picture (isn't it beautiful?):

post-310118-0-56895000-1298254664.jpg

Each rectangle is a div tag and I'll refer to them by their colours. Black is the main content of the page and has to be below red which is the footer. However I have an image (green) within red which extends over the text in black but must always lie below the text. The text in black is contained within a span tag (but this could be a div as well if it needs to be).

My question is, is it possible to give black a z-index of, say, 1; red a z-index of 2; green a z-index of 3; and the text a z-index of 4?

This would make the above picture possible. However, browsers won't allow a child element to have a higher z-index than its parent so the above is not possible. The text always has an inherited z-index of 1, and therefore lies below green.

Is there a workaround?

P.S. I realise this can be a bit confusing to understand, hence the picture.

7 answers to this question

Recommended Posts

  • 0

Yeah unforunately it's actually not - assuming that the text is inside the black div. It doesn't matter what the z-index of the text is set to, it will always inherit the z-index of its parent div and will therefore have a lower z-index than the green div.

This is my example code which outputs the diagram above but shows that the text always lies below the green div even though it has a higher z-index:

<html>
  <head>
    <style type="text/css">
      #black {
        position: relative;
        width: 400px;
        height: 400px;
        background-color: black;
        z-index: 1;
      }

      #text {
        color: white;
        z-index: 4;
      }

      #red {
        position: relative;
        margin-top: -100px;
        margin-left: 25px;
        width: 350px;
        height: 200px;
        background-color: red;
        z-index: 2;
      }

      #green {
        position: absolute;
        top: -150px;
        right: 50px;
        width: 50px;
        height: 200px;
        background-color: green; 
        z-index: 3;
      }
    </style>
  </head>
  <body>
    <div id="black">
      <span id="text">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
      </span>
    </div>

    <div id="red">
      <div id="green"></div>
    </div>
  </body>
</html>

  • 0

Would it be possible to separate the text in the black div from the div itself, put it into a div of its own as a child of <body> or whatever, and then give that a higher z-index, background: transparent; and absolute position things to line them up? Just a thought.

  • 0

Yeah I thought of that, and it's basically a good idea, but the content of the black div is loaded by AJAX and so the length is undetermined. I'd have to use javascript to measure the height of the div containing the text and then make the black div that same height. Perfectly possible, yes. But is it really necessary?

  • 0

I found this to be an intriguing question, so I gave this a try. Have a look at it here.

Here's how it's done:

  • There's no background set on #black, the background is simply transparent. Instead, the background color is done by adding an extra element (#black:before) and absolutely positioning it so that it has the same position and size as its parent. This element then gets the black background color set.
  • To make the black background layer #black:before go behind the text, its z-index is set to a negative value. Since the text is separate from the background, this z-index causes the text to be on top of the background layer.
  • #red and #green can now assume negative z-indexes between the z-indexes of #black and #black:after to make them appear between the background and the text.
    If only one background box is needed, you might want to consider using #black:after instead and get rid of the meaningless HTML.

Known issues:

  • Doesn't work in Internet Explorer. :pinch:
    It appears that in IE, the :after element is created as a child rather than a sibling and as such, #red and #green cannot be placed between those two z-indexes.

The problem lies in setting the position and size of the background layer when this layer is not a child of the text layer. If the text layer has a fixed position and size, you can simply copy these over to the background layer. However, with flexible layer heights, I don't see a way to match the size of a sibling.

We couldn't do it for layout columns and so we had to use techniques like faux columns or floats with clears to make two columns appears to have equal heights. It appears that this problem is very similar to the columns issue.

Perhaps someone finds a better solution?

  • 0

It is possible just like I mentioned earlier. Don't need js height calculations. Need to assign z index only to one element.

&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">t;html xmlns="http://www.w3.org/1999/xhtml">t;head&gt;
	&lt;title&gt;&lt;/title&gt;
	&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
	&lt;style type="text/css"&gt;

*	{
	margin: 0;
	padding: 0;
}
body	{
	padding: 20px;
}
#wrap	{
	width: 920px;
	margin: 0 auto;
}
#content	{
	color: #fff;
	background: #000;
	padding-bottom: 20px;
}
#content p	{
	z-index: 2;
	padding: 50px;
	position: relative;
}
#footer	{
	padding: 20px;
	height: 150px;
	background: #f00;
	margin: -50px 50px 0 50px;
}
#green	{
	width: 50px;
	float: right;
	height: 240px;
	display: block;
	margin-top: -150px;
	background: green;
}

	&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;div id="wrap"&gt;
	&lt;div id="content"&gt;
		&lt;p&gt;Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.&lt;/p&gt;
	&lt;/div&gt;
	&lt;div id="footer"&gt;
		&lt;span id="green"&gt;
		&lt;/span&gt;
	&lt;/div&gt;
&lt;/div&gt;

&lt;/body&gt;

&lt;/html&gt;

  • 0
  On 21/02/2011 at 16:54, sweetsam said:

It is possible just like I mentioned earlier. Don't need js height calculations. Need to assign z index only to one element.

&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">.

Your version is very good, but I'm having trouble recreating it with my demo... This is my new code:

&lt;html&gt;
  &lt;head&gt;
    &lt;style type="text/css"&gt;
      #black {
        position: relative;
        width: 400px;
        height: 400px;
        background-color: black;
      }

      #text {
        color: white;
        z-index: 5;
      }

      #red {
        position: relative;
        margin-top: -100px;
        margin-left: 25px;
        width: 350px;
        height: 200px;
        background-color: red;
      }

      #green {
        position: absolute;
        top: -150px;
        right: 50px;
        width: 50px;
        height: 200px;
        background-color: green;
      }
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id="black"&gt;
      &lt;span id="text"&gt;
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
      &lt;/span&gt;
    &lt;/div&gt;

    &lt;div id="red"&gt;
      &lt;div id="green"&gt;&lt;/div&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;

The green div is still above the text.

Ah don't worry, it works now. I just added "position: relative" under #text and it works now - thanks a lot!

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Yes, and the reason is the defaults is has. The masses have no interest to change settings etc. It feels cluttered by default. The default home/NTP feels cluttered with so much stuff from MSN. The sidebar has too many buttons with Microsoft services. The default search engine is Bing. Just compare Edge defaults with Chrome defaults. The masses open Edge or are "forced" to open it, they don't like what they see and close it and go back to Chrome.
    • PrivaZer 4.0.106 by Razvan Serea PrivaZer is a PC cleaner that helps you master your security and freedom at home and at work. PrivaZer permanently and irretrievably erases unwanted traces of your past activity on your computer and on your storage devices (USB keys, external drive, and so on) which prevents others from retrieving what you have done, watched, streamed, visited on internet, freeing up valuable hard disk space, and keeping your PC running secure. PrivaZer key features: Deep Cleaning: PrivaZer thoroughly cleans your PC by removing unnecessary files, traces of activity, and potential privacy risks. Advanced Scan Modes: With multiple scan modes, including Quick and Deep scans, PrivaZer ensures comprehensive cleaning tailored to your needs. Customizable Cleaning: PrivaZer allows you to customize cleaning settings, so you can choose exactly what to clean and what to keep. Privacy Protection: PrivaZer safeguards your privacy by securely erasing traces of your online and offline activities, including browsing history and temporary files. Secure File Deletion: PrivaZer securely deletes sensitive files beyond recovery, ensuring your confidential data remains private. Startup Manager: PrivaZer helps you control which programs launch at startup, improving boot times and overall system performance. Automatic Updates: PrivaZer regularly updates its cleaning algorithms to adapt to new threats and ensure effective protection. Scheduled Cleanups: PrivaZer offers the convenience of scheduling automated cleanups, so your PC stays optimized without manual intervention. Portable Version: PrivaZer offers a portable version, allowing you to carry it on a USB drive and clean any PC without installation. Detailed Reports: PrivaZer provides detailed reports after each cleanup, giving you insights into the space reclaimed and the areas cleaned. File Shredder: PrivaZer includes a file shredder feature to securely delete files, making data recovery impossible even with specialized tools. Context Menu Integration: PrivaZer integrates with the context menu, enabling quick and easy access to cleaning functions from any file or folder. Multi-Language Support: PrivaZer supports multiple languages, making it accessible to users worldwide. Automatic Traces Detection: PrivaZer automatically detects traces of activity on your PC, ensuring thorough cleaning without manual intervention. System Restore Point Creation: PrivaZer creates system restore points before cleaning, allowing you to revert changes if needed. Disk Health Analysis: PrivaZer analyzes disk health and alerts you to potential issues, helping you prevent data loss and maintain system stability. Browser Extensions Cleanup: PrivaZer cleans up browser extensions and add-ons, improving browser performance and security. File Association Management: PrivaZer helps you manage file associations, ensuring files open with the correct programs for optimal usability. Intuitive User Interface: PrivaZer features an intuitive user interface, making it easy for both novice and advanced users to optimize their PCs for better performance and privacy. PrivaZer 4.0.106 changelog: New cleanup : BAM (Background Activity Monitor) Improved cleanup : Clipboard Improved UI Download: PrivaZer 4.0.106 | Portable PrivaZer ~30.0 MB (Freeware, paid upgrade available) View: PrivaZer Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • This was cool back in the day when done properly - loved having icons of specific devices.
    • Microsoft quietly burying a massive Windows 7 hardware driver feature as Windows 11 kills it by Sayan Sen Last month Microsoft announced a big update for Windows hardware drivers. The company declared that it was killing Windows Device metadata and the Windows Metadata and Internet Services (WMIS). For those wondering what it is, device metadata, as the name suggests, is the collection of additional, user-facing information that an original equipment manufacturer (OEM) provides about a hardware device. The feature was introduced with Windows 7 and can include stuff like icons, logos, descriptive texts, among other things, that help the Windows UI display details about such devices in places like Task Manager or Device Manager. This was a huge deal back in the day when Windows 7 debuted. The company called the feature "Device Stage" and Microsoft described it as a "new visual interface" that essentially worked like a "multi-function version of Autoplay where it displays all the applications, services, and information related to your device." It is often considered synonymous with the Windows "Devices and Printers" Control Panel applet. Neowin did an in-depth overview of the feature when it first launched which you can find in its dedicated article here. The Windows OS was able to obtain the device experience metadata from the WMIS, but now that the feature is being deprecated, Microsoft has begun removing information about Device Stage from its official support documents. Neowin noticed while browsing that a support article regarding automatic Windows hardware drivers was updated for Windows 11 and 10 sometime last year after the release of Windows 11 24H2. Previously, this article was geared for Windows 7 and was much longer. It also contained information about Device Stage, which, as mentioned above, was a headlining feature on Windows 7. In the said article, the section "If Windows can't find information about your device in Device Stage" has been deleted. You can find the archived version of the support page here. Aside from shortening the amount of information on the page, Microsoft has also added some more details on it. The company has now tried to define what the Microsoft Basic Display Adapter is, how updating drivers through Device Manager works, as well as a thorough and detailed troubleshooting section for common hardware driver errors on Windows, including one for USB-C. You can find all the new details on the updated support page here on Microsoft's website.
  • Recent Achievements

    • Veteran
      Yonah went up a rank
      Veteran
    • First Post
      viraltui earned a badge
      First Post
    • Reacting Well
      viraltui earned a badge
      Reacting Well
    • Week One Done
      LunaFerret earned a badge
      Week One Done
    • Week One Done
      Ricky Chan earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      481
    2. 2
      +FloatingFatMan
      264
    3. 3
      snowy owl
      238
    4. 4
      ATLien_0
      232
    5. 5
      Edouard
      176
  • Tell a friend

    Love Neowin? Tell a friend!