james6848
james6848

Reputation: 1667

Can changes in an element's width modify another element's font-size using jQuery?

I have a container whose width is fluid (depending on the size of the browser window), though it has a max-width of 950px. The container has a nested header h1 element which has some text as a strapline.

I want to somehow make this header text get smaller as the container gets narrower (using jQuery).

I think it'll work something like this:

I'd like it to work dynamically during the browser resize if possible.

Any ideas?

Cheers, James

Upvotes: 0

Views: 275

Answers (2)

manji
manji

Reputation: 47968

$(window).resize(function(){
    var widthRatio =  $('#container').width()/950; 
    $('#header1').css('font-size', 24 * widthRatio);
    });
  • 'container' is the id of the container
  • 'header1' is the id of the inner h1 element
  • 24 is the default font size for H1 elements

Upvotes: 1

Adam Bellaire
Adam Bellaire

Reputation: 110429

The method you've outlined should work just fine. The conversion from string to number should be handled using parseFloat, since the font size is returned in (IIRC) em, e.g.:

var hText = $("#hText").css("font-size");
var textSize = parseFloat(hText);

Yes, it is possible to do this during the browser resize, using

(window).bind('resize', function () {
    // Your implementation
});

Upvotes: 1

Related Questions