Reputation: 20320
How can I animate text on a webpage and increase its size while keeping the center anchored at a point? This is what I have tried:
http://jsfiddle.net/wnn2v023/1/
but as can be seen, the anchor point is at (0, 0) instead of the text center. I tried playing around with text-align
but couldn't get desired result.
HTML:
<button id="button">
Begin
</button>
<div id="main">
<div id="div">
Hello World!
</div>
</div>
CSS:
#main
{
position: relative;
}
#div
{
position:absolute;
font-size:0em;
}
@-webkit-keyframes my-animation {
0% { font-size: 0em; }
100% { font-size: 5em; }
}
.effect {
-webkit-animation: my-animation 1s; /* Safari 4+ */
animation: my-animation 1s;
animation-fill-mode: forwards;
}
JS:
var e = document.getElementById("button");
var div = document.getElementById("div");
e.addEventListener("click", function()
{
div.className = "effect";
});
Note that I cannot make any changes to the main
div. Also I found using the font-size
to animate does not give a very smooth animation.
Upvotes: 1
Views: 623
Reputation: 286
You need to specifiy margin:0 auto, try this:demo changed only the css part,
#main {
position: relative;
}
#div {
margin:0 auto;;
text-align: center;
width:82%;
}
@-webkit-keyframes my-animation {
0% {
font-size: 0em;
}
100% {
font-size: 5em;
}
}
.effect {
-webkit-animation: my-animation 1s;
/* Safari 4+ */
animation: my-animation 1s;
animation-fill-mode: forwards;
}
`
Upvotes: 0
Reputation: 240878
Rather than animating the font-size
property, animate transform: scale()
.
Set the desired font-size
on the text along with transform: scale(0)
and then animation it to its default scale of transform: scale(1)
:
document.getElementById('button').addEventListener("click", function() {
document.querySelector('.text').classList.toggle("effect");
});
.container {
position: relative;
}
.text {
position: absolute;
transform: scale(0);
font-size: 5em;
}
@-webkit-keyframes grow {
100% { transform: scale(1); }
}
@keyframes grow {
100% { transform: scale(1); }
}
.effect {
-webkit-animation: grow 1s forwards;
animation: grow 1s forwards;
}
<button id="button">Begin</button>
<div class="container">
<span class="text">Hello World!</span>
</div>
Upvotes: 2