medBo medBo - 6 months ago 14
jQuery Question

Keep ratio of a div when the font size changes

I have a div with a fixed width and height and a font size of 16px like the following

<div id="mydiv" style="font-size:16px;height:40px;line-height:40px;width:160px;background:orange;text-align:center;">
hello world
</div>


I have an input text that allow changing the font size

<input type="text" id="input">

<button> change size </button>


JS :

$('button').on('click', function(){

var value = $('#input').val();

$('#mydiv').css('font-size', value + 'px');

});


If you enter a size of 30 for example the text will be out of the div, what I want to achieve is to keep the ratio, so when the font-size changes I want the div to change dimension keeping the aspect ratio. How I can do that ?

https://jsfiddle.net/mody5/x6t2dn3e/1/

Answer

You need to re-calculate the div width, height and line-height when you change its font-size. By updating just its font-size alone, nothing else will be changed.

$('button').on('click', function() {
  var div = $('#mydiv');

  // These methods return the value unit-less, so they'll be integers
  // if defined.
  var currentWidth = div.width();
  var currentHeight = div.height();

  // Parsing the values to make sure you got integers.
  var currentFontSize = parseInt(div.css('font-size'), 10);
  var currentLineHeight = parseInt(div.css('line-height'), 10);
  var value = parseInt($('#input').val(), 10);

  var newFontSize = value + 'px';

  // Here we keep the ratio between width and height, considering
  // the current and new font-size.
  var newWidth = ((currentWidth * value) / currentFontSize) + 'px';
  var newHeight = ((currentHeight * value) / currentFontSize) + 'px';
  var newLineHeight = ((currentLineHeight * value) / currentFontSize) + 'px';

  // Applying all the styles at once.
  div.css({
    fontSize: newFontSize,
    width: newWidth,
    height: newHeight,
    lineHeight: newLineHeight
  });
});

Demo