使用CSS3动画堆叠顺序更改

时间:2014-08-21 20:55:44

标签: css css3 css-animations

我正在关注making a ribbon with CSS的指南。但是,我试图通过向该位置添加CSS3动画来修改它,如此JSFiddle中所示。

正如您所看到的,通过动画,主要功能区元素落后于:before& :after伪元素,而不是它应该在它们之上(没有动画)。我已经尝试在所有元素上明确设置z-index,但它似乎并没有影响到这一点。有谁知道为什么会发生这种情况,或者我能做些什么来解决它?为了记录,我通过最新的谷歌浏览器观看,并不担心目前的跨浏览器兼容性。谢谢!

这是功能区代码:

.ribbon {
    font-size: 16px !important;
    /* This ribbon is based on a 16px font side and a 24px vertical rhythm. I've used em's to position each element for scalability. If you want to use a different font size you may have to play with the position of the ribbon elements */
    width: 50%;
    position: relative;
    background: #ba89b6;
    color: #fff;
    text-align: center;
    padding: 1em 2em;
    /* Adjust to suit */
    margin: 2em auto 3em;
    /* Based on 24px vertical rhythm. 48px bottom margin - normally 24 but the ribbon 'graphics' take up 24px themselves so we double it. */
    /*CODE I ADDED*/
    animation: flyRibbon 30s linear infinite;
    -webkit-animation: flyRibbon 30s linear infinite;
}
.ribbon:before, .ribbon:after {
    content:"";
    position: absolute;
    display: block;
    bottom: -1em;
    border: 1.5em solid #986794;
    z-index: -1;
}
.ribbon:before {
    left: -2em;
    border-right-width: 1.5em;
    border-left-color: transparent;
}
.ribbon:after {
    right: -2em;
    border-left-width: 1.5em;
    border-right-color: transparent;
}
.ribbon .ribbon-content:before, .ribbon .ribbon-content:after {
    content:"";
    position: absolute;
    display: block;
    border-style: solid;
    border-color: #804f7c transparent transparent transparent;
    bottom: -1em;
}
.ribbon .ribbon-content:before {
    left: 0;
    border-width: 1em 0 0 1em;
}
.ribbon .ribbon-content:after {
    right: 0;
    border-width: 1em 1em 0 0;
}

这是动画代码:

@keyframes flyRibbon {
    100% {
        transform: translateX(200vw);
        -webkit-transform: translateX(200vw);
    }
}

2 个答案:

答案 0 :(得分:2)

在功能区周围添加div并将动画css应用于它而不是h1元素应该解决此问题。

HTML:

<div class="container">
    <h1 class="ribbon">
       <strong class="ribbon-content">Everybody loves ribbons</strong>
    </h1>
</div>

CSS:

.container {
    animation: flyRibbon 30s linear infinite;
    -webkit-animation: flyRibbon 30s linear infinite;
}

JSFiddle

答案 1 :(得分:2)

这不是错误。对于create stacking contextsz-index创建堆叠上下文的元素,这是.ribbon的指定行为,因为它具有transform(在动画中)。使用transform时,元素将成为堆叠上下文的根,并且不能在其下方放置子框。

作为没有额外标记的解决方法,您可以显示内部contatiner块并将其放置在功能区末端上方,就像在此example中一样。