Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the text content in a div increase and decrease in font size repeatedly?

I’m wondering if it’s possible to have the text content of a div increase and decrease in font size repeatedly every second. This would give an effect where the text seems to move closer to the viewer before moving back, ideally it would be a smooth transition and wouldn’t look like a 2 frame gif.

This is my attempt using Javascript to change the font size every second:

<div id="textdiv">ZOOM</div>
<script>
function zoomtext(){
   var textdiv = document.getElementById("textdiv");
   textdiv.style.fontSize = "20px";
   textdiv.style.fontSize = "25px";

   setTimeout(zoomtext, 1000);
}
</script>

This isn’t working, and I’m not sure that this code would result in a smooth transition. Perhaps it’s possible to make a smooth transition by changing the font by tenths of a pixel (for example: 20px, 20.1px, 20.2px …and so on until 25px, and then decreasing it back to 20px in the same way).

I’m worried that method might result in a Javascript function running constantly, which might slow down my page.

Is there a better way to get this effect?

like image 301
Emily Avatar asked Feb 04 '26 12:02

Emily


1 Answers

Use CSS transitions with scale transformation. Font-size transitions are never smooth, and transitions on transform are cheap.

.grow { 
    transition: all .2s ease-in-out;
}
.grow:hover {
    transform: scale(1.5);
}

Repetition can be accomplished through CSS3 animations:

.grow {
  width: 100px;
  text-align: center;
  animation: grow-animation 2s linear infinite;
}

@keyframes grow-animation {
  0% { transform: scale(1); }
  50% {transform: scale(2); }
  100% {transform: scale(1); }
}
like image 123
Harmen Avatar answered Feb 07 '26 01:02

Harmen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!