我似乎无法让 CSS:hover 正常工作。
当您将鼠标悬停在“我的网站”上时,我试图显示一个不透明度设置为 0 的文本框。我用图像实现了类似的效果,但无法仅使用文本。
我试过 a:hover 和 p:hover,都不起作用。
<div class="site">
<p style="padding: 10px;"><a href="myWebsite.html" id="Home">My Website</a></p>
<p id="siteText">This is my primary website where all the information you might require on me is available! This site is also a demonstration of my work; however, external reviews are available on the website!</p>
</div>
#siteText {
background-color: rgba(255,255,255,0.8);
text-align: center;
width: 475px;
padding: 15px;
position: absolute;
left: 50%;
opacity: 0;
transform: translate(-50%, -50%);
}
#Home a:hover + #siteText {
opacity: 1;
}
最佳答案
您的标记存在几个基本问题。
- 您有
a
元素在p
元素然后siteText
内容。因此,选择器a:hover + #siteText
无法工作,因为a
和#siteText
是 < em>不是直系 sibling 。 - 在您的 CSS 中,您有
#Home a:hover
,其中#Home
是a
元素.这应该只是#Home:hover
。 #siteText
的一些其他样式(转换、位置等)导致它出现在屏幕外,因此我在下面删除了它们以演示调整后的 HTML/CSS 的工作原理.
此外,我建议您不要将 ID 用于此类事情。相反,以全局时尚的方式思考。也就是说,使用可重复的类/标记组合,而不必不断向您的 CSS 添加更多 ID。在下面的示例中,我将 #siteText
(ID) 更改为 .tooltip
的 class - 并且调整了 CSS,以便现在,只要你有一个 a
元素紧跟着一个类为 tooltip
的元素,你就会有一个有效的悬停效果。
下面是一个工作片段:
.tooltip {
background-color: rgba(255, 255, 255, 0.8);
text-align: center;
width: 475px;
padding: 15px;
opacity: 0;
}
.pad-vertical {
display: inline-block;
padding: 10px 0;
}
a:hover + .tooltip {
opacity: 1;
}
<div class="site">
<div><a class="pad-vertical" href="myWebsite.html" id="Home">My Website</a>
<p class="tooltip">This is my primary website where all the information you might require on me is available! This site is also a demonstration of my work; however, external reviews are available on the website!</p>
</div>
</div>
更新
我向 a
元素添加了一些填充。请注意,我已经通过一个类再次完成了此操作,因此您可以在可能需要像这样填充的 a
元素上使用该类。
关于html - CSS:尝试显示不透明文本框时出现悬停问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50378645/