:元素在悬停时重叠我的按钮文本

时间:2016-01-15 12:41:46

标签: html css

我有一个背景颜色和文字颜色设置的按钮。我喜欢做的是,当用户将鼠标悬停在按钮上时,背景将从下到上进行动画处理,并将文本颜色更改为背景颜色。

为了简化代码,我没有把我喜欢的瞬态应用于CSS属性。我知道更改按钮后台代码更容易,但我打算使用瞬态来更改悬停时的namespace Application Class Module { public function onBootstrap(MvcEvent $e) { $serviceManager = $e->getApplication()->getServiceManager(); $service = $serviceManager->get('Service\From\Other\Module'); } } 高度。

所以我有以下代码,但当我将鼠标悬停在按钮上时,:before重叠了我的按钮文字。

我也尝试使用:before,但没有运气。你认为这个问题有什么解决办法吗?

z-index
body {
  background: #111;
}
.btn {
  color: #FFF;
  background: #333;
  border: none;
  font-size: 18px;
  font-weight: bold;
  padding: 18px 60px;
  position: relative;
}
.btn:before {
  display: block;
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 0;
  background: #FFF;
}
.btn:hover {
  color: #333;
}
.btn:hover:before {
  height: 100%;
}

4 个答案:

答案 0 :(得分:3)

您可以在不添加额外跨度的情况下实现所需效果。通过将前后伪元素用于背景颜色并正确定位它们。

要将伪元素放在文本后面,请在元素上设置正z-index,在伪元素上设置负z-index。

java.util.Calendar

参考Nicolas Gallagher的这篇文章,该文章更详细地解释,请参阅“伪背景位置”http://nicolasgallagher.com/an-introduction-to-css-pseudo-element-hacks/部分。

另请参阅动作:https://jsfiddle.net/j9whmcmz/2/

如果将背景颜色应用于.btn本身,则此技术不起作用。

我猜选择你的毒药,两种解决方案都可以解决问题。

答案 1 :(得分:2)

您需要添加额外的<span>元素,该元素将保留在伪元素之前:

span {
  position: relative;
  z-index: 1;
}

fiddle

答案 2 :(得分:2)

试试这个:

body {
  background: #333;
}
.btn {
  color: #FFF;
  background: #333;
  display: inline-block;
  position: relative;
  overflow: hidden;
  -webkit-transition: color 0.3s ease-in-out;
  transition: color 0.3s ease-in-out;
}
.btn span {
  display: inline-block;
  padding: 18px 60px;
  border: none;
  font-size: 18px;
  font-weight: bold;
  z-index: 10;
  position: relative;
}
.btn:after {
  display: block;
  content: '';
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  max-height: 0;
  background: #FFF;
  height: 100%;
  z-index: 9;
  -webkit-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}
.btn:hover {
  color: #333;
}
.btn:hover:after {
  max-height: 100%;
  top: 0;
}
<a href="#" class="btn"><span>Do Stuff</span></a>

答案 3 :(得分:1)

解决方案如果非常明显 - 按钮的内容也应该是绝对定位的。然后浏览器将它们正确地排在后面。

编辑:也许我的格式和样式不是最好的情况,但它是快速更新您的代码以获得想法

body {
  background: #111;
}
.btn {
  color: #FFF;
  background: #333;
  border: none;
  font-size: 18px;
  font-weight: bold;
  padding: 18px 60px;
  position: relative;
}
.btn span {
  display: block;
  content: '';
  position: absolute;
  top: 18px;
  left: 0px;
  width: 100%;
  text-align: center;
}
.btn:before {
  display: block;
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 0;
  background: #FFF;
}
.btn:hover {
  color: #333;
}
.btn:hover:before {
  height: 100%;
}
<br />
<a href="#" class="btn"><span>Do Stuff</span></a>

相关问题