RomanK RomanK - 5 months ago 22
CSS Question

CSS Border Animation Works For Whole Div Content

I have a div with a border and forms inside of it. I decided to animate the border so it would pulse. My Code:

<div class="main">
<div class="border">

-Text Here-

</div>
</div>


My CSS:

@keyframes pulse {
0% { opacity: 0; animation-timing-function: ease-in;}
20% { opacity: .2; animation-timing-function: ease-in;}
40% { opacity: .4; animation-timing-function: ease-in;}
45% { opacity: .8; animation-timing-function: ease-in;}
50%% { opacity: 1; animation-timing-function: ease-in;}
50%% { opacity: 1; animation-timing-function: ease-out;}
55% { opacity: .8; animation-timing-function: ease-out;}
60% { opacity: .4; animation-timing-function: ease-out;}
80% { opacity: .2; animation-timing-function: ease-out;}
100% { opacity: 0; animation-timing-function: ease-out;}
}

.border {
border-radius: 25px;
border: 8px solid #2C3E50;
animation-name: pulse;
animation-duration: 4s;
animation-iteration-count: infinite;
}

.main{
padding: 50px;
width: 500px;
height: 500px;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
}


The problem is that the animation works for the whole content of the div + the border, I would like it to work for only the border not the content inside of it. I know this is probably an easy fix, but I'm not good with CSS.

Also, how would I make the animation start when the user click anywhere inside the div and keep going even when click outside div. Thanks in advance.

Answer

Instead of using opacity which will affect the entire div, use border-color. Fiddle.

@keyframes pulse {
        0%   { border-color: rgba(0, 255, 255, 1); }
        50%  { border-color: rgba(0, 255, 255, 0); }
        100% { border-color: rgba(0, 255, 255, 1); }
}

.border {
  border-radius: 25px;
  border: 8px solid #2C3E50;
  animation: pulse 2s infinite;
}  

If you want to toggle on & off when that specific div is clicked you could toggle the class with a function like:

function changeclass() {
   var blah = document.getElementById("border")
   if (blah.className=="border"){
       blah.className = "";
   }
   else{
       blah.className="border";
   }
} 

and your html would be:

<div class="main">
<div id="border" onclick="changeclass()">
-Text Here- 
</div>
</div>

If you want to toggle on when clicked inside and then toggled off when clicked anywhere on the page, then add an eventlistener to the document like this:

document.addEventListener('click', function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;   
        if (target.className == "border"){
            target.className = "";
        }
        else{
            document.getElementById("border").className = "border";
        }
}, false);

and your html would be:

<div class="main">
<div id="border">
-Text Here-
</div>
</div>

Opacity is the 4th position in rgba so use 0.0-1.0 as the value. Less being more transparent.

Comments