2017-09-26 322 views
0

我有一个按钮,它带有一个放置在下面的伪元素以创建点击效果。我写这个代码:伪元素在CSS变换中从下方移动到父元素上方

button { 
 
    appearance: none; 
 
    --webkit-appearance: none; 
 
    background-color: #0070c9; 
 
    border-radius: .3em; 
 
    border: none; 
 
    color: white; 
 
    display: inline-block; 
 
    font: inherit; 
 
    font-size: 1.5em; 
 
    padding: 5px 10px; 
 
    position: relative; 
 
    text-transform: uppercase; 
 
} 
 
button::after { 
 
    background-color: #005496; 
 
    border-radius: .3em; 
 
    bottom: -.2em; 
 
    content: ''; 
 
    height: 100%; 
 
    left: 0; 
 
    position: absolute; 
 
    width: 100%; 
 
    z-index: -1; 
 
} 
 
button:active, button:focus { 
 
    outline: none; 
 
} 
 
button:active { 
 
    transform: translateY(0.1em); 
 
} 
 
button:active::after { 
 
    bottom: -.1em; 
 
}
<button>Button</button>

当点击该按钮时,伪元件成为按钮的背景;我希望浅色背景在转换发生时和之后保留在伪元素上。是否有一个原因,伪元素在文本下移动,但在按钮的背景之上?

注意:我没有在我的原始代码中使用任何供应商加前缀的CSS,我只是在此页面上添加了--webkit-appearance: none;;我将在后期使用后处理器来处理这个问题。

编辑

的按钮看起来像左边当不在活动状态,右图像中活跃的状态。

Unpressed button Pressed button

我不想让按钮变暗,当它处于活动状态。我希望背景保持不变。

我想按钮看起来像这样被点击时:

What it should look like

回答

2

我已经加入伪元素前::以及再移位的z指数:前后:当按钮处于活动状态时,在伪元素之后。我还在按钮文本周围添加了一个范围,并添加了一个相对位置和一个3的z-index,以使其位于伪元素的前面。

button { 
 
    appearance: none; 
 
    background:none; 
 
    --webkit-appearance: none; 
 
    border-radius: .3em; 
 
    border: none; 
 
    color: white; 
 
    display: inline-block; 
 
    font: inherit; 
 
    font-size: 1.5em; 
 
    padding: 5px 10px; 
 
    position: relative; 
 
    text-transform: uppercase; 
 
} 
 
button span { 
 
    position:relative; 
 
    z-index:3; 
 
} 
 
button::before, button::after { 
 
    border-radius: .3em; 
 
    content: ''; 
 
    height: 100%; 
 
    left: 0; 
 
    position: absolute; 
 
    width: 100%; 
 
} 
 
button::before { 
 
    background-color: #0070c9; 
 
    top: 0; 
 
    z-index: 2; 
 
} 
 
button::after { 
 
    background-color: #005496; 
 
    bottom: -.2em; 
 
    z-index: 1; 
 
} 
 
button:active, button:focus { 
 
    outline: none; 
 
} 
 
button:active span { 
 
    bottom: -.2em; 
 
} 
 
button:active::before { 
 
    z-index:2; 
 
    background:none; 
 
} 
 
button:active::after{ 
 
    z-index:1; 
 
    background-color: #0070c9; 
 
}
<button><span>Button</span></button>