Search code examples
jqueryscreen-resolution

Change CSS Class height and width in javascript depending on screen res


I want the size of a div class 'content' to change depending on the size of the users' screen resolution.

So far Ive written this javascript

function resize()
{

    if ((screen.width>1024)) { $(".content").style.width = 560 + "px"; $(".content").style.height = 315 + "px" }
    if ((screen.width>1280)) { $(".content").style.width = 640 + "px"; $(".content").style.height = 360 + "px" }
    else { $(".content").style.width = 853 + "px"; $(".content").style.height = 480 + "px" }
};

and obviously in the html I have the class '.content'

why is this code not working?


Solution

  • Your specific issue here is that you are mixing jQuery and raw javascript.

    To set the width of an element with jQuery, use the width() or css() method:

    $(".content").width(560);
    $(".content").css('width',560);
    

    Having said that, you may be better off looking at the browser size, not screen resolution. Shouldn't your content respond to the size of my browser, regardless of my screensize? I don't keep my browser fullscreen.

    Lastly, look at css media queries even to respond to the browser size. There are much better ways of doing this.