Home > Enterprise >  show and hide a div with transition in CSS without using JavaScript
show and hide a div with transition in CSS without using JavaScript

Time:09-17

I want to perform transition property to show and hide the div without the involvement of JavaScript. I used the following code:

div {
  background-color: rgb(238, 190, 118);
  height: 200px;
  border: 2px solid rgb(255, 230, 0);
  font-size: 50px;
  text-align: center;
  animation: hide_div 5s forwards;
}

@keyframes hide_div {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<div>
  Hide Div
</div>

this is done by animation property. when the given code is executed div is hidden after 5s but there is no way to show it again without refreshing the browser.

Does anyone have an idea how it will be done? let me know, please.

CodePudding user response:

If you want it to show automatically. Use alternate infinite on animate css prop.

div {
  background-color: rgb(238, 190, 118);
  height: 200px;
  border: 2px solid rgb(255, 230, 0);
  font-size: 50px;
  text-align: center;
  animation: hide_div 5s alternate infinite;
}

@keyframes hide_div {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<div>
  Hide Div
</div>

If you a user to be able to control when the div is shown you could use a checkbox and the next sibling combinator " " combined with transition (rather than animation).

div {
  background-color: rgb(238, 190, 118);
  height: 200px;
  border: 2px solid rgb(255, 230, 0);
  font-size: 50px;
  text-align: center;
  transition: opacity 5s;
  opacity: 0;
}

input:checked   div {
  opacity: 1
}
<label for="cb">Show The Div</label><input id="cb" type="checkbox">

<div>
  Hide Div
</div>

CodePudding user response:

You can use infinite instead of forwards:

animation: hide_div 5s infinite;

That should be enough for your request :)

div {
  background-color: rgb(238, 190, 118);
  height: 200px;
  border: 2px solid rgb(255, 230, 0);
  font-size: 50px;
  text-align: center;
  animation: hide_div 5s infinite;
}

@keyframes hide_div {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<div>
  Hide Div
</div>

  • Related