Wilson Page

Front-end developer at FT Labs, within the Financial Times. Chatting about JavaScript, CSS, Web-Apps and other goodness. Follow me on Twitter.
Front-end developer at FT Labs, within the Financial Times. Chatting about JavaScript, CSS, Web-Apps and other goodness. Follow me on Twitter.
  • Contact
  • ask me anything
  • rss
  • archive
  • CSS 3D transforms messing with your z-index

    About 3D Tranforms

    3D transforms are useful even when you are not creating a design that utilises 3D space. Setting a 3D transform on an element causes hardware accelerated graphics to kick in, making animation super smooth. This is not that evident on powerful desktop platforms but on mobile devices the difference is astonishing!

    To trigger hardware acceleration on an element you can apply a class like this:

    /* Trigger hardware-acceleration */
    .uses3d { -webkit-transform: translate3d(0, 0, 0); -webkit-transform-style: preserve-3d; }
    


    The z-index problem

    I ran into a major issue in particular versions of webkit that causes z-index to be ignored on an element and its children when a 3D property is specified. No matter what I did I could get these particular hardware accelerated elelements to respect their original z-index.


    The fix

    After running round in circles and setting ridiculously high and low z-indexes on elements to no avail I stumbled across the solution. It seemed that within the hardware accelerated layer created z-index was being ignored, so I decided to try setting a pixel value on that “3D” elements z-axis. It worked! In certain browsers (I found Chrome and Blackberry Playbook) the z-index must be reinforced with a z-axis property. Like so:

    #a{
        width: 300px;
        height: 300px;
        background: red;
        position: absolute;
        left: 0px;
        top: 0px;
        z-index: 1;
    
       /* reinforce z-index in 3D space */
        -webkit-transform: translate3d(0, 0, 1px);
    }
    


    Working example

    In this example try commenting out the ‘preserve-3d’ styling on the container and notice how the z-index is respected. With the ‘preserve-3d’ styling on try uncommenting the ‘-webkit-transform’ property on each child element. Notice how styling is preserved. This bug is evident for me on Chrome v16.0.912.75.

    http://jsfiddle.net/qkLWH/20/

    • January 20, 2012 (6:56 am)
    • 8 notes
    • #css
    • #css3
    • #3d tranforms
    1. voodoojuiced likes this
    2. wilsonpage posted this
    Tweet
© 2011–2013 Wilson Page