位于其父级下的位置元素:after

时间:2018-03-13 10:01:46

标签: css css3 css-selectors pseudo-element

我想在鼠标悬停在按钮下时添加背景。我想利用:after伪选择器以避免包含更多标记。

button {
  position: relative;
  z-index: 1;
  padding: 1rem 2rem;
  background: blue;
  color: white;
  border: none;
  transition: 0.25s ease all;
}

button:after {
  opacity: 0;
  content: "";
  z-index: -1;
  position: absolute;
  top: 5%;
  left: 5%;
  width: 100%;
  height: 100%;
  background: red;
  transition: 0.25s ease opacity;
}

button:hover:after {
  opacity: 1;
}
<button>Hello world</button>

正如您所看到的那样,当悬停红色背景时,按钮的背景位于按钮的背景上,这不是我想要的。

关于如何实现这种效果的任何想法?

以下是演示:https://codepen.io/cesalberca/pen/EEVMVx

2 个答案:

答案 0 :(得分:3)

只需从按钮中删除z-index:

&#13;
&#13;
// helpers.njk
{% macro formatDate(date) %}
{{ date.split and date.split('-').reverse().join('.') or date }}
{% endmacro %}
... // another macros

// usage
{% import 'helpers.njk' as helpers %}
{{ helpers.formatDate('2018-03-12') }}
&#13;
button {
  position: relative;
  padding: 1rem 2rem;
  background: blue;
  color: white;
  border: none;
  transition: 0.25s ease all;
}

button:after {
  opacity: 0;
  content: "";
  z-index: -1;
  position: absolute;
  top: 5%;
  left: 5%;
  width: 100%;
  height: 100%;
  background: red;
  transition: 0.25s ease opacity;
}

button:hover:after {
  opacity: 1;
}
&#13;
&#13;
&#13;

按评论编辑(按钮中需要一个范围):

&#13;
&#13;
<button>Hello world</button>
&#13;
button {
  position: relative;
  z-index: 1;
  border: none;
  background: transparent;
  padding: 0;
}

button span {
  display: inline-block;
  padding: 1rem 2rem;
  background: blue;
  color: white;
  transition: 0.25s ease all;
  position: relative;
  z-index: 2;
}

button:after {
  opacity: 0;
  content: "";
  z-index: 1;
  position: absolute;
  top: 5%;
  left: 5%;
  width: 100%;
  height: 100%;
  background: red;
  transition: 0.25s ease opacity;
}

button:hover:after {
  opacity: 1;
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

无需额外元素。

button {
  border: 0;
  outline: 0;
  background: none;
  position: relative;
  display: inline-block;
  padding: 1rem 2rem;
  background: blue;
  color: white;
  transition: all .25s ease;
  cursor: pointer;
}
button:after {
  content: "";
  opacity: 0;
  position: absolute;
  top: 5%;
  left: 5%;
  width: 100%;
  height: 100%;
  background: red;
  z-index: -1;
  transition: opacity .3s ease;
}

button:hover:after {
  opacity: 1;
}
<button>Submit</button>