html - 伪元素在 CSS 变换上从父元素下方移动到父元素上方

标签 html css css-transforms

我有一个带有伪元素的按钮,我将其放置在下方以创建点击效果。我写了这段代码:

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

最佳答案

我还添加了一个::before 伪元素,然后在按钮处于事件状态时移动了 :before 和 :after 伪元素的 z-index。我还在按钮文本周围添加了一个跨度,并添加了一个相对位置和一个 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>

关于html - 伪元素在 CSS 变换上从父元素下方移动到父元素上方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46435713/

相关文章:

CSS - 字母后面的阴影

javascript - 多个图标大小,如何、何时何地使用它们?

html - css 单选按钮切换背景

javascript - 如何在JointJs中动态设置字体大小?

javascript - 如何让 <div> 中的两个元素调用不同的函数?

html - 只转换 css 中的转换?

html - 导航栏与容器的宽度不同

html - 垂直滚动时固定列。水平滚动时不固定。纯CSS

php - 扩展 PHP Markdown 以接受 CSS 类名

html - 使用透视和变换时如何控制z-index?