我有一个图像,其中一个绝对定位的链接位于其顶部。当图像悬停时我有过渡效果,但当链接悬停时它们会丢失。
HTML
<div class="imagediv">
<img src="#">
<a href="#">Text</a>
</div>
CSS
.imagediv img {
transition: transform 0.2s linear;
}
.imagediv img:hover{
transform: scale(1.2);
filter: grayscale(50%);
}
.imagediv a {
position: absolute;
z-index: 2;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
如何制作,以便在链接悬停时保留我对图像悬停的效果?
答案 0 :(得分:1)
更改您的CSS选择器,以便在.imagediv
悬停而不是img
本身时触发。
.imagediv img {
transition: transform 0.2s linear;
}
.imagediv:hover img {
transform: scale(1.2);
filter: grayscale(50%);
}
答案 1 :(得分:1)
在:hover
imagediv
.imagediv {
position: relative; /* added so link position relates to imagediv */
}
.imagediv img {
transition: transform 0.2s linear;
}
.imagediv:hover img {
transform: scale(1.2);
filter: grayscale(50%);
}
.imagediv a {
position: absolute;
color: white;
z-index: 2;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
&#13;
<div class="imagediv">
<img src="http://placehold.it/600x100/f00">
<a href="#">Text</a>
</div>
&#13;
答案 2 :(得分:1)
如果您能够切换img
text
元素的顺序,则可以使用常规兄弟选择器,但它仅适用于以下兄弟
a:hover ~ img {
transform: scale(1.2);
filter: grayscale(50%);
}
.imagediv img {
transition: transform 0.2s linear;
}
.imagediv img:hover{
transform: scale(1.2);
filter: grayscale(50%);
}
.imagediv a {
position: absolute;
z-index: 2;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
a:hover ~ img {
transform: scale(1.2);
filter: grayscale(50%);
}
<div class="imagediv">
<a href="#">Text</a>
<img src="#">
</div>
.imagediv img {
transition: transform 0.2s linear;
}
.imagediv img:hover{
transform: scale(1.2);
filter: grayscale(50%);
}
.imagediv a {
position: absolute;
z-index: 2;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
答案 3 :(得分:1)
要解决的一些问题:
:hover
样式移动到容器。relative
位置,以便absolute
链接可以在内部居中,否则偏移将相对于视口。
.imagediv {
display: inline-block;
position: relative;
}
.imagediv img {
transition: transform 0.2s linear;
}
.imagediv:hover img {
transform: scale(1.2);
filter: grayscale(50%);
}
.imagediv a {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="imagediv">
<img src="//unsplash.it/200">
<a href="#">Text</a>
</div>
如果您需要整个块可以点击,可以使用flexbox。
.imagediv {
display: inline-block;
position: relative;
}
.imagediv img {
transition: transform 0.2s linear;
}
.imagediv:hover img {
transform: scale(1.2);
filter: grayscale(50%);
}
.imagediv a {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
}
<div class="imagediv">
<img src="//unsplash.it/200">
<a href="#">Text</a>
</div>