0

I have a simple alert box styled which contains a clickable button that closes the alert box. The code looks like this:

.alert {
    position: relative;
    padding: 1.2rem 2rem;
    background-color: rgba(0, 0, 0, 0.01);
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: var(--border-radius);
}

.alert.hidden {
    display: none;
}
<div class="alert">
  This is an alert box.
  <button onclick="this.parentNode.classList.add('hidden')">Close</button>
</div>

<div class="alert">
  Another one
  <button onclick="this.parentNode.classList.add('hidden')">Close</button>
</div>

As you can see, the boxes can be closed by clicking on the button and adding the .hidden class to the parent element. How can I add in a simple fade out for this event?

Moreover, I would also like to create another class like .alert.fade-in which would fade in the alert box on the first page load.

So far, I added some transitions to the .alert class, but it had no noticeable difference.

Note: The alert boxes need to stop taking up space when they are hidden. So visibility would not work.

darkhorse
  • 8,192
  • 21
  • 72
  • 148

1 Answers1

3

.alert {
    position: relative;
    padding: 1.2rem 2rem;
    background-color: rgba(0, 0, 0, 0.01);
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: var(--border-radius);
}

.alert.hidden {
    animation:1s fadeMe forwards;
}

@keyframes fadeMe {
  0% { opacity:1; }
  99% { padding: 1.2rem 2rem; height:auto; }
  100% { opacity:0; height:0px; padding:0; }
}
<div class="alert">
  This is an alert box.
  <button onclick="this.parentNode.classList.add('hidden')">Close</button>
</div>

<div class="alert">
  Another one
  <button onclick="this.parentNode.classList.add('hidden')">Close</button>
</div>

As for the fade in on page load, doing that with CSS is tricky because as soon as the CSS is loaded the animation will play whether or not the page is fully loaded. You can set an animation-delay but your really need javacsript to make sure everything is ready to go before you start making animations.

MomasVII
  • 4,641
  • 5
  • 35
  • 52