Scale text to fit browser size with transition
P粉459578805
P粉459578805 2023-09-08 11:11:22
0
1
695

I have some text that I want to resize to 100% of the browser when hovering over a button. How can I make this text fit in the browser/container?

I know that using font size you can do something like font-size:100vw but the animation of font-size is very unstable so I can't use this method.

http://jsfiddle.net/0n15mfyL/

For those wondering about jitter, it's noticeable when the font is scaled down: http://jsfiddle.net/rbk48upd/

P粉459578805
P粉459578805

reply all(1)
P粉729518806

I am considering requestAnimationFrame()

const 
  hoverMe        = document.querySelector('#hover-me')
, animTextSizing = document.querySelector('#anim-text-sizing')
, txtSizeStart   = parseInt(window.getComputedStyle(animTextSizing).getPropertyValue('font-size'))
  ;
let sizeLimit = 0,  currentTxtSize = txtSizeStart
  ;
hoverMe.onmouseover =_=>
  {
  sizeLimit = document.body.clientWidth;
  animGrow();
  }
hoverMe.onmouseout =_=>
  {
  sizeLimit = txtSizeStart;
  currentTxtSize++
  animReduce();
  }
function animGrow()
  {
  animTextSizing.style['font-size'] = `${++currentTxtSize}px`;

  if ( animTextSizing.clientWidth < sizeLimit)
    requestAnimationFrame(animGrow);
  }
function animReduce()
  {
  animTextSizing.style['font-size'] = `${--currentTxtSize}px`;

  if ( currentTxtSize > sizeLimit)
    requestAnimationFrame(animReduce);
  }
* {
  margin  : 0;
  padding : 0;
}
#anim-text-sizing {
  font-size   : 30px;
  width       : fit-content;
  white-space : nowrap;
  background  : #aabfe5;
  }
#hover-me {
  position   : fixed;
  background : red;
  color      : white;
  top        : 50%;
  left       : 50%;
  padding    : .5rem;
  cursor  : zoom-in;
  }
  <div id="hover-me">Hover me</div>
  <div id="anim-text-sizing"> Welcome to this Page </div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template