我正在尝试在鼠标悬停时淡入淡出叠加层。在正常情况下,有一个不透明度为 0.4 的覆盖 div,我希望鼠标悬停时其不透明度为 0。但当我这样做时,它一直闪烁。我尝试了两种解决方案;我使用过渡作为第一个解决方案,使用 @keyframes 作为第二个解决方案,但它们都没有帮助。这是我尝试过的:
第一个解决方案;
.MainPageCountry {
display: flex;
}
.MainPageCountryContent {
position: relative;
}
.overlay {
position: absolute;
top: 0;
left: 0;
background-color: #000;
width: 100%;
height: 100%;
z-index: 2;
opacity: 0.4;
transition: 0.5s ease;
}
.overlay:hover {
opacity: 0;
}
.overlay-country-name {
font-size: 20px;
margin: 0;
padding: 3px 6px;
border-radius: 5px;
color: #fff;
position: absolute;
bottom: 15px;
left: 15px;
background-color: #000;
z-index: 3;
}
第二个;
.MainPageCountry {
display: flex;
}
.MainPageCountryContent {
position: relative;
}
.overlay {
position: absolute;
top: 0;
left: 0;
background-color: #000;
width: 100%;
height: 100%;
z-index: 2;
opacity: 0.4;
}
.overlay:hover {
animation: fadeOverlay 1s forwards;
}
@keyframes fadeOverlay {
10% {
opacity: 0;
}
}
.overlay-country-name {
font-size: 20px;
margin: 0;
padding: 3px 6px;
border-radius: 5px;
color: #fff;
position: absolute;
bottom: 15px;
left: 15px;
background-color: #000;
z-index: 3;
}
和 HTML;
<div class="MainPageCountry">
<div class="MainPageCountryContent">
<img class="MainPageCountryImage" src="..." alt="flag" />
<div class="overlay"></div>
<p class="overlay-country-name">Country Name</p>
</div>
</div>
我怎样才能实现这个目标?
同意@mokorana,你的第一个解决方案运行良好。这是它的更简洁的版本。
.d1 {
position: relative;
width: 200px;
cursor: pointer;
}
.d1 img {
display: block;
max-width: 100%;
}
.d1 p {
box-sizing: border-box;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding-bottom: 10px;
margin: 0;
color: white;
background-color: #0000004f;
font-size: 2em;
transition: 0.5s ease;
display: flex;
justify-content: center;
align-items: end;
text-shadow: 0 0 5px black;
}
.d1:hover p {
background-color: transparent;
}
<div class="d1">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Bandera_de_Espa%C3%B1a.svg" alt="flag" />
<p>Spain</p>
</div>