如何让CSS Hover Transform与相对定位一起工作

时间:2017-06-28 15:16:02

标签: html css css3 css-transitions

JSFiddle

我的标题文字旁边有一个箭头。将鼠标悬停在文本上方时,箭头会进行转换。它适用于position: absolute,但我需要它与position: relative一起使用。

我如何实现这一目标?

#container {
  width: 130px;
  border: 1px solid red;
  padding: 10px;
}

#container h2:after {
  transition: all 1s ease
}

#container:hover h2:after {
  transform: translateX(30px);
  transition: all 1s ease;
}

#container h2:after {
  content: "->";
  position: absolute;
  /* It currently works with absolute positioning, but I want it to work with relative positioning. */
}
<div id="container">
  <h2>Go to my website</h2>
</div>

4 个答案:

答案 0 :(得分:1)

#container h2::after设为display: inline-block

#container h2::after {
  transition: all 1s ease;
  display: inline-block;
}

旁注:即使h2:after没有错,用beforeafter创建的元素也是用2个冒号写的,而伪类(如{ {1}})仅使用1个冒号。

答案 1 :(得分:0)

将两个h2:after样式组合成更干净的代码,将变换更改为margin-left for css以允许转换效果并将位置更改为相对于h2。如果您有任何问题,请告诉我。

&#13;
&#13;
#container {
  width: 130px;
  border: 1px solid red;
  padding: 10px;
}

#container h2:after {
  transition: all 1s ease;
  content: "->";
  position: relative;
}

#container:hover h2:after {
  margin-left: 30px;
  transition: all 1s ease;
}
&#13;
<div id="container">
  <h2>Go to my website</h2>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

只需将display:inline-block添加到伪元素

即可

&#13;
&#13;
#container {
  width: 130px;
  border: 1px solid red;
  padding: 10px;
}

#container h2:after {
  transition: all 1s ease
}

#container h2:after {
  content: "->";
  position: relative;
  display: inline-block;
  /* It currently works with absolute positioning, but I want it to work with relative positioning. */
}

#container:hover h2:after {
  transform: translateX(30px);
  transition: all 1s ease;
}
&#13;
<div id="container">
  <h2>Go to my website</h2>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

只需使用margin-left而不是转换

https://jsfiddle.net/MAXXALANDER/L8ce3m4q/

Image