CSS overlay effect keeps flickering on mouse over

38 views Asked by At

I am trying to do fade an overlay on mouse over. In normal conditions there is an overlay div with 0.4 opacity, i want this to be 0 opacity on mouse over. But when i do this, it keeps flickering. I tried two solutions; I used transitions as the first solution and the @keyframes as the second solution but none of them helped. Here are what I have tried:

first solution;

.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;
}

and the second;

.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;
}

and the 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>

how can i achieve this?

1

There are 1 answers

0
Brett Donald On

Agree with @mokorana that your first solution is working fine. Here is a tidier version of it.

.flag {
  display: inline-block;
  position: relative;
  width: 200px;
  cursor: pointer;
  margin: 0.5em;
}

.flag img {
  display: block;
  width: 100%;
}

.flag p {
  margin: 0;
  box-sizing: border-box;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: end;
  color: white;
  font-size: 2em;
  text-shadow: 0 0 5px black;
  padding-bottom: 10px;
  background-color: #0000004f;
  transition: 0.5s ease;
}

.flag:hover p {
  background-color: transparent;
}
<span class="flag">
  <img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Bandera_de_Espa%C3%B1a.svg" alt="flag" />
  <p>Spain</p>
</span>

<span class="flag">
  <img src="https://upload.wikimedia.org/wikipedia/commons/2/27/Flag_of_Moldova.svg" alt="flag" />
  <p>Moldova</p>
</span>