• 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

    • I have tried that registry 'trick' from that video already. It doesn't work at all in Win11 for me   Yes it's a 3rd party app... that I am only using because of Microsoft breaking user customization in Windows 11. So yes... the is a Windows 11 issue. As of now to me, Microsoft has made a huge mistake with this in Windows 11.   The current font option in Windows 11 are terrible. They are just missing. People that want to use their own computer the way they want to, they need to avoid 11.
    • It's been an age since I did desktop support, but here goes: You have an issue with Windows 11, which is fair.  You are using a freeware 3rd party app to make modifications to the default Windows 11.  Since an update, this 3rd party application no longer plays nice with Windows 11.  And this is somehow Windows 11's fault? Sorry, not buying that this is a Windows 11 problem... it's a customization issue that has just appeared, but standard 3rd party support.   Clearly you're upset.  You can't make Windows do anything, just like you can't make MacOS run Explorer or Linux run Nintendo games natively.  And I know people are going to say "sure, it's possible..." but those aren't defining elements of the OS.  You can't have animated backgrounds in Windows 11 natively -- so it's trash amirite??? I did quick searches about changing the default fonts and there are ways to do it, and clearly 3rd party freeware apps can do it (basically my guess is they're making registry changes on your behalf) and clearly they're having issue.   You can make your computer do a lot of things, but sometimes you get what you pay for. Did a quick search and don't see an easy option in Windows 10 either.  Some of these links - ironically - are for Windows 10.  They still apply. Here's a video tutorial of how it can be done without a 3rd party:   Same reference here with a bit more detail: https://www.howtogeek.com/716407/how-to-change-the-default-system-font-on-windows-10/ Once the font is chosen, the size can be changed via personalization from my understanding. Hope this helps.
    • Videomass 5.0.26 by Razvan Serea Videomass is not just a common converter, it features file concatenation, time trimmer, ability to create thumbnails, tiled mosaics and animated giffs from movies; it has sophisticated GUIs for video filters, previews for video stabilization, resizing, croping, transposing, color equalization. It features PEAK, RMS and EBU audio normalization with streams indexing capabilities, a volume analyzer, audio preview and many more interesting features… For the people that are familiar with FFmpeg, it has a highly customizable preset manager with the possibility to easily make your own presets through the GUI and adapt this to your specific needs or create new presets using the FFmpeg command line. For less experienced people there are also ready-to-use presets. It offers out-of-the-box all possible file formats like MP4, M4V, M4A, MKV, AVI, OGV, WEBM, MP3, AC-3, WAV, OPUS, FLAC, OGG and encoders like MPEG-4, H.264/AVC, H.265/HEVC, VP8, VP9, LIBAOM-AVI, VORBIS, PCM, LAME, ALAC, etc. Also you can copy audio or video streams (lossless mode) without re-encoding, or extract audio from videos and much more! Main features No ads Multi-Platform, work on Linux, MacOs, Windows, FreeBsd. Batch processing. Queue management (only available for Presets Manager and A/V Conversions). Advanced log file management. Multi-panels, switch between panels using keyboard shortcuts. Audio/video processing using advanced tools and sophisticated filters interfaces. While downloading audio or video you can now do other transcoding tasks. Multi languages support (English, French, Italian, Russian, Dutch, Portuguese-BR, simplified Chinese, Spanish-ES, Spanish-CU, Spanish-MX) Conversions and transcoding Drag and drop to add multiple files simultaneously. Fully customizable presets and profiles. Possibility to create your new presets and profiles from scratch. Has useful presets to start with. Using the Presets Manager, you can set any format and codec supported by your FFmpeg build. Media file info (from FFprobe) and streams analyzer (from volumedetect). Shows the estimated time of arrival during encodings. Concatenate, merge media files losslessly. Create Slideshows. Extract images from video. Ability to switch between different FFmpeg builds. Has useful graphical tools for evaluating the supported features of a specific FFmpeg build. Audio stream mapping using selectable indexes. You can set both audio and video to copy when you just want to convert formats (lossless process). Timeline editor to slice time segments or trim the duration of your media even without re-encoding and therefore without loss of quality. It has GUI video filters such as: Resize Crop Transpose Deinterlace Denoise Stabilize Equalize Audio filters for volume normalization such us: PEAK, RMS and EBU-R128 normalizers. PEAK and RMS volume analysis reporting. Ability to select specified audio streams in videos to apply volume normalization. and much more… Videomass 5.0.26 changelog: Fixed yt-dlp preferences tab issue #372 Enabled import of the external «yt_dlp» package also on the standalone executable built by Pyinstaller. Improved handling of the yt-dlp executable (yt-dlp.exe on Windows) which now provides some automation and useful information for the users. Added «Whale» browser to the supported browser list for cookie automations. Update it_IT i18n, thanks to @bovirus Update zh_CN i18n, thanks to @userwljs Removed API functionality for download operations. Now only the yt-dlp executable is used for download operations. The API is still needed and will only be used for statistics extraction and format code listing. Fixed #374 Added «FLAC resampler» new preset. Notes: FFmpeg is not included in this archive. Before launching the application, ensure you have a compatible version of FFmpeg for your system architecture (requires ffmpeg.exe, ffprobe.exe, and ffplay.exe, version 5.1 or newer). For more details and downloads, visit: Gyan's FFmpeg builds page BtbN's FFmpeg GitHub releases page Antivirus False Positive Detection Some antivirus programs may mistakenly flag Videomass.exe as malicious. These are false positives. To resolve this, submit the Videomass.exe file to your antivirus vendor for further analysis and request a false positive review. Download: Videomass 5.0.26 | 18.4 MB (Open Source) Links: Videomass Home Page | Screenshots | Other OSes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      abortretryfail earned a badge
      Week One Done
    • First Post
      Mr bot earned a badge
      First Post
    • First Post
      Bkl211 earned a badge
      First Post
    • One Year In
      Mido gaber earned a badge
      One Year In
    • One Year In
      Vladimir Migunov earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      489
    2. 2
      +FloatingFatMan
      261
    3. 3
      snowy owl
      244
    4. 4
      ATLien_0
      222
    5. 5
      Edouard
      189
  • Tell a friend

    Love Neowin? Tell a friend!