Yi Ren
Yi Ren

Reputation: 841

how to increase border line from the center using css animation

I'm playing around with CSS animation, and I was wondering if there's a way to make a vertical line (with certain height) to grow in length automatically when the page loads. Idealy I want the vertical line to grow from the middle and grow from both top and bottom to a specific height. So far I can only make it increase its length from top to bottom. Here's what I have:

.vertical-line {
	margin-left: 100px;
	background: red;
	width: 8px;
	border-radius: 4px;
	animation: grow 4s forwards;
}

@keyframes grow {
	0% {
		height: 10px;
	}
	100% {
		height: 100px;
	}
}
<!DOCTYPE html>
<html>
	<head>	
		<title>Creating Vertical borders using animation/javascript</title>	
	</head>
	<body>
		<div class="vertical-line"></div>
	</body>
</html>

Upvotes: 2

Views: 3555

Answers (3)

Karthi Keyan
Karthi Keyan

Reputation: 137

what is wrong witn your code is you are simply increasing the height. In order to grow on both side while increasing height you have to move that element towards the opposite side
Example: if you are increasing height 100px then you have to move opposite for 50px

CSS:

#cool
{
height:10px;
width:10px;
border-radius:4px;
margin-left:10%;
background-color:#431;
margin-top:20%;
animation:grow 3s forwards;
position:relative;
}

@keyframes grow
{
0% {
    height: 0px;
    top:0;
}
100%{
    height: 200px;
    top:-100px;
}
}

</style>

HTML:

<div id=cool>

</div>

</body>

for height 100px moving the element top -50px . Taken half of it, because to show the growth on both side. if top -100px then it will grow from the bottom.
I hope this helps

Upvotes: 1

keziah
keziah

Reputation: 574

Try this,

<div class="vertical-line"></div>
<style>
    .vertical-line {
        position: absolute;
        top: 0;
        border: 5px solid red;
        width: 10px;
        border-radius: 4px;
        animation: grow 3s infinite alternate;
    }

    @keyframes grow {
        0% {
            width: 0px;
            height: 0px;
        }
        100% {
            width: 20px;
            height: 100%;
        }
    }
</style>

Upvotes: 0

Himmel
Himmel

Reputation: 3709

One way you could accomplish this would be to set the initial position of the line in the very center, and then have it extend towards the top and the bottom of the viewport.

.myLine {
  position: absolute;
  left: 50vw;
  top: 50vh;
  width: 1px;
  height: 1px;
}

You can then add a class, extended, via JavaScript that changes the position and height, thus making it appear to extend vertically from the center.

.extended {
    top: 0vh;
    bottom: 100vh;
    height: 100%;

    transition: all 3s ease;
}

Using JavaScript, as I've done here, you can set a brief timeout, and add the class after the timeout has finished.

var el = document.querySelector('.myLine');

setTimeout(function() {
 el.classList.add('extended');
}, 300);

See my example codepen.

Upvotes: 1

Related Questions