2017-09-26 46 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>