如何在CSS中正确实现 #ID:hover{},而不会在其他HTML元素上出错?

How can I properly implement #ID:hover{} in CSS with no missalignment on other HTML elements?

提问人:DevNightshade 提问时间:10/26/2023 更新时间:10/26/2023 访问量:42

问:

所以,我第一次尝试元素,到目前为止我没有遇到任何问题。但是现在,我想要一个 div 框,它有多个链接,就像 一样,目的是有一个用作动画的功能。<div><a><img>#Image:hover

实施也进展顺利,但现在我遇到了我的问题,我没有发现任何具体的问题......每当我将鼠标悬停在 img 元素上时,img 元素都会错位。现在我想知道我可以实现什么,这样它就不会错位......

我有这个CSS部分:

#Icons {
    margin: 8px 0 0;
    padding: 0;
    display: block;
    background-color: transparent;
    min-height: 43px;
    height: 43px;
    max-height: 43px;
}

#Image {
    margin: 0;
    padding: 0;
    width: 40px;
    height: 40px;
}

#Image:hover {
    margin: 0;
    padding: 0;
    width: 43px;
    height: 43px;
}

#Media {
    margin: 0 4px;
    display: inline-block;
    min-width: 43px;
    width: 43px;
    max-width: 43px;
    min-height: 43px;
    height: 43px;
    max-height: 43px;
}

和这个 HTML 部分:

<p id="HeaderTwo">Reachable under</p>
<div id="Icons">
    <a id="Media" href="#"><img id="Image" src="../img/discord.png" /></a>
    <a id="Media" href="#"><img id="Image" src="../img/gmail.png" /></a>
    <a id="Media" href="#"><img id="Image" src="../img/telegram.png" /></a>
    <a id="Media" href="#"><img id="Image" src="../img/youtube.png" /></a>
</div>

我尝试将 folling 位包含在一些 CSS 元素中,希望它能用作框限制器或 sth。类似,因此不会发生错位。

min-width: 43px;
width: 43px;
max-width: 43px;
min-height: 43px;
height: 43px;
max-height: 43px;
HTML CSS 悬停 对齐方式

评论

1赞 Paulie_D 10/26/2023
ID 是唯一的,不应多次使用。
0赞 Paulie_D 10/26/2023
另外,请解释一下你所说的错位是什么意思。
0赞 DevNightshade 10/26/2023
如果你使用我的代码片段,你可以看到 <div> “Icons” 行向下移动,远离 <p> 句子

答:

-1赞 LSE 10/26/2023 #1

要避免元素调整布局大小,请使用 .transform scale

现在,除了您的具体问题外,请考虑以下修复程序:

  • 避免使用 ID 进行样式设置(此外,ID 必须是唯一的)
  • 悬停动画是告诉用户图像是可点击的,因此触发器应该在标签上<a>

.image {
  width: 40px;
  height: 40px;
  transition: transform .3s;
  will-change: transform;
}

.media {
  display: inline-block;
  margin: 0 4px;
}

.media:hover .image {
  transform: scale(1.075);
}
<div class="icons">
    <a href="#" class="media"><img class="image" src="https://source.unsplash.com/random?1" /></a>
    <a href="#" class="media"><img class="image" src="https://source.unsplash.com/random?2" /></a>
    <a href="#" class="media"><img class="image" src="https://source.unsplash.com/random?3" /></a>
    <a href="#" class="media"><img class="image" src="https://source.unsplash.com/random?4" /></a>
</div>

评论

1赞 DevNightshade 10/26/2023
谢谢,这成功了。但是,我不明白您所说的“触发器应该在 <a> 标签上”是什么意思。想解释一下吗?
0赞 LSE 10/26/2023
没关系。在为链接设置悬停效果动画时,应使用 .否则,如果将鼠标悬停在该链接内的另一个元素上,则图像不会动画化。与此示例中一样,即使将鼠标悬停在文本链接上,图像也不会动画化:jsfiddle.net/xaon3dyk/3 。这是你相应地做到这一点的方式:jsfiddle.net/3074qpsb/1img:hover {}a:hover img {}
0赞 DevNightshade 10/26/2023
我明白了,所以它有点像CSS的“扩展”属性。谢谢,很高兴知道!