Philip
Philip

Reputation: 39

resize div but keep dimensions

I want a <div> that reacts and fits the screen window size. The <div> is supposed to have the dimensions 2:3 So that the height is 3:3 and the width is 2:3. It is easy enough to make it in css by writing width: 200px; and height:300px;.

The thing is that I want the height of the <div> to resize depending on the screensize. And also I want the text inside of it to resize. I know it is possible by javascript or jQuery, but I really don't know how. Something like taking the height and split it in three, and then times two, and then make .css({'width',newWidth});

And it should be about the same thing with the text inside of it.

I found the correct way to do it. I had to change a little bit, but it works now.

$(window).resize(function() {
var ratio = 0.6;
$('#hovsa').width($(window).height() * ratio).height($(window).height());
// instead of directly using "$(window).width() * ratio", you can call a method to
// calculate width and height each time window is resized.
})

I have changed the width to be height * ratio and it worked very well. The only thing I need to do now is to make the fontsize going the same way as well.

Upvotes: 0

Views: 3090

Answers (3)

Mordhak
Mordhak

Reputation: 2656

As said before, it is better for you to use percent values if the size you want will always be the same.

But, in other cases, if you need a fixed size for your div, or a calculated one, you can listen for window resizing event and do your css modification :

$(window).resize(function() {
    var ratio = 0.8;
    $('#divId').width($(window).width() * ratio).height($(window).height() * ratio);
    // instead of directly using "$(window).width() * ratio", you can call a method to
    // calculate width and height each time window is resized.
})

Upvotes: 3

Zwik
Zwik

Reputation: 654

Heres a method in Javascript using jQuery that would do the resize you want.

function resize(divToResizeId, newHeight) {
    var divToResize = $("#" + divToResizeId);
    var resizeRatio = newHeight / divToResize.height();

    var currentFontSize = divToResize.css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum * resizeRatio;

    divToResize.height(newHeight);
    divtoResize.width(divtoResize.width() * resizeRatio);
    divToResize.css('font-size', newFontSize);
}

Upvotes: 0

Aymeric
Aymeric

Reputation: 1175

I think the best way to make those "resize" is using only relative values (e.g. percentage, em) this way you'll be able to keep the same look & feel for your web application.

If you want to use fixed values like pixels, you can create different .css files and use those depending on client screen resolution but it implies a lot of work and it couldn't worth it.

Hope this help.

Aymeric.

Upvotes: 0

Related Questions