Corné Strijkert
Corné Strijkert

Reputation: 290

Resizing child DIV equal to parent DIV

I have a DIV with width 400px and height 200px. Inside this div is another div with some text at position 50,50 and font-size 14px;

When the parent DIV resizes (for example to 600px x 300px), i want that the text-size inside the child DIV resizes too (to a larger font-size), equal to the resized parent DIV.

How can i do that with jQuery and HTML?

Upvotes: 1

Views: 12975

Answers (4)

Cristian Bitoi
Cristian Bitoi

Reputation: 1557

when the parent dives size becomes (600 / 300) from (400 / 200) for example, you should apply a javascript function to the child div like so

function resizeFont(parentElementId, childElementId, newWidth) {

    currWidthParentElement = parseFloat( $(parentElementId).width() ); // get current width
    currChildFontSize = parseInt( $(childElementId).css('font-size') ); // get font size for child   

    percentaRaise = (newWidth - ceil(currWidthParentElement)) * (100/ceil(currWidthParentElement)); // calculate how much parent increase

    // calculate and apply new font size
    newFontSize = currChildFontSize * percentaRaise/100 + currChildFontSize;

    $(childElementId).css(newFontSize);


}

is seems tricky but is simple algebra. I hope thihs will help you

Upvotes: 1

user1618236
user1618236

Reputation:

There is an extension for jquery that allows resize to be fired on elements like it would on the window itself.

The extension: Jquery Resize Plugin

So something like this will do the trick:

$("#parent").resize(function(){
    var newFontSize = $("#parent").height() * 0.07 
    $("#child").css("font-size",newFontSize +"px");
});

Check out this JsFiddle for an example: http://jsfiddle.net/Mm3jr/1/

Upvotes: 0

rafaelcastrocouto
rafaelcastrocouto

Reputation: 12161

http://codepen.io/rafaelcastrocouto/pen/EiFIL

var div = $('div');
$(window).on('resize', function(){  
  var u = div.width() / 200;
  div.css('font-size', u +'em');  
});

Upvotes: 0

user934902
user934902

Reputation: 1204

make the child div width and height 100%

childDiv {
 display:block;
 width: 100%;
 height: 100%;
 position:relative //so you dont lose the positioning of your text
}

Upvotes: 3

Related Questions