• 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

    • It gave OEMs all kinds of stuff to put effort into that did nothing about bad drivers that crashed the system.
    • Yes, because Google's ad platform dominates the internet and most sites use Google's ad platform. Microsoft cares about their own ad platform. And they whitelist their ads. Edge is still on mv2 on desktop but they have officially announced they will stop supporting it. They haven't announced the date, but it is on their roadmap. Microsoft HAS the resources to keep it, but they have announced they will remove it unlike other chromium based browsers like Brave and Opera which have announced they will try to keep it. They postponing it in an attempt maybe to gain some market share from Chrome, but their end goal is the same, the deprecation of mv2. https://learn.microsoft.com/en-us/microsoft-edge/extensions-chromium/developer-guide/manifest-v3#manifest-timeline-for-microsoft-edge-and-partner-center
    • I'll say this again:  This hasn't changed since Windows 10.  This customization issue is not unique to Windows 11.   Windows 10 was released about 10 years ago.  I didn't look at changing default fonts in Windows 8 or 7.  Most (sane) people would look for supportability -- you might have the desired customization in those OSs but not able to play games, apps, that one typically gets the OS for.  No one is going to trade off getting an ancient OS just so they can have larger fonts but not be able to play games or run apps.   There are many options that are not exposed in the default UI because they have a lot more potential harm than benefit.  Doesn't mean they don't exist.  Hence, registry changes. "What's the harm by leaving it in Settings?"  Imagine if you changed the default font to something unreadable.  How would you change it back if you can't read anything?  The settings UI allows one to change size and style, but not font, so you'd still be able to read it.  Changing the font itself to Wingdings might render an OS unusable. Now YOU might be savvy enough to make that change and/or undo it, but that's why it's not exposed in simplistic UI and instead is moved to registry changes. Your 3rd party app is most likely causing conflict with the registry as it wants to make its own changes.  It's not voodoo magic here, that's typically what these apps do.  I'd bet you a beer if I spin up a new VM for Windows 11 and try my links above with no Winaero Tweaker it'd work just fine.  Introduction of 3rd party apps is always suspect -- who knows what else it's doing.  
    • 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
  • Recent Achievements

    • Dedicated
      Epaminombas earned a badge
      Dedicated
    • 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
  • Popular Contributors

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

    Love Neowin? Tell a friend!