2

I am trying to make a div the full width and height of a browser window, here is the code I have. It doesnt work.

jQuery:

<script type="text/javascript">
    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();

    $('#lordy').css('height', viewportHeight + 'px');
    $('#lordy').css('width', viewportWidth + 'px');

    $(window).resize(function() {
        var viewportWidth = $(window).width();
        var viewportHeight = $(window).height();

        $('#lordy').css('height', viewportHeight + 'px');
        $('#lordy').css('width', viewportWidth + 'px');
    });

HTML

<div id="lordly"></div>

CSS

#lordly { 
    background-color: #CB0011;
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Ghozt
  • 267
  • 4
  • 13
  • 1
    Can you include a fiddle, it is easier to see what is going wrong with your JS then. Alternatively see my CSS answer. – Mike Oram Sep 30 '13 at 08:01
  • 4
    Your javascript always refers to "#lordy" while your html and css refer to the ID "lordly" (notice the addional l). This might be the issue – Marcus Krahl Sep 30 '13 at 08:04
  • 1
    It can be done using CSS only. There are a lot of similar question on SO already: [1](http://stackoverflow.com/questions/1719452/how-to-make-a-div-always-full-screen), [2](http://stackoverflow.com/questions/3276226/how-to-make-a-full-screen-div-and-prevent-size-to-be-changed-by-content) – kasitan Sep 30 '13 at 08:04
  • Just use CSS: `height: 100%; width: 100%;`. Make sure that's set on all the parent elements required, including `html` and `body` – Rory McCrossan Sep 30 '13 at 08:05
  • Thanks @MarcusKrahl this was the problem! – Ghozt Sep 30 '13 at 09:28
  • Does this answer your question? [How to make a
    always full screen?](https://stackoverflow.com/questions/1719452/how-to-make-a-div-always-full-screen)
    – Adam Harte Nov 15 '19 at 02:05

1 Answers1

2

You can just use CSS for this, no need for JS.

You need to make sure you have set HTML and body to 100% width and height first. see below:

html,
body {
    width: 100%;
    height: 100%;
}

#lordly {
   width: 100%;
   height: 100%;
}

As long as #lordly is a direct child of body this will work.

also worth noting you should remove margin and padding on html and body to ensure cross browser compatibility

Edit: For completeness, the issue with your JS is that your jQuery selector is looking for #lordy where as your Id is actually lordly - you are missing the 'l'

Mike Oram
  • 765
  • 8
  • 21
  • The problem with my JS code was I misspelt the div name, but I will be using css instead so thanks for this – Ghozt Sep 30 '13 at 08:18