1

When I open a page I want to get full-height background image. Like this

I haven't started using jQuery yet, so if you could help me with basic js. This is what I tried so far, but it wasn't working.

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
    <script type="text/javascript" src="assets/js/basic.js"></script>
    <meta charset="UTF-8"> 
  </head>
  <body>
    <header>
      <div id="front-page" class="window_height_picture" onload="get_window_height()">
      </div>
    </header>
  </body>   
</html>

And this is my .js file:

function get_window_height() {
    var window_height = window.innerHeight;
    document.getElementById('front-page').style.height = window_height + 'px';
}

I did search for this, but couldn't find what I was looking for. Can you tell me where I was wrong, or provide me with a better code?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
stevs
  • 9
  • 5

2 Answers2

5

Pure CSS Solution

No need for JavaScript at all. Use the vh viewport length unit in your CSS.

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

CSS Values and Units Module Level 3

This unit specifically sets the length to be equal to a percentage of the viewport height (where 1vh is 1% of the viewport height, etc.) Here you want 100vh (100% of the viewport height):

#front-page {
    height: 100vh;
}

An popular answer of mine which I posted to a different question here on Stack Overflow goes into a lot of detail about what the vh unit is: Make div 100% height of browser window.

Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

You may have noticed that in the example you provided, wordpress.com theme uses a background-size: cover; for the background image.

See MDN's doc or this friendly tutorial.

  • Yes, I used that css property, but if i figured it out, I think that only works for the given height and width, it can't set it to window height, am I right? – stevs Aug 11 '15 at 15:29
  • No that doesn't set the height to the viewport's height indeed. Just wanted to make sure that you didn't miss this very handy property :-) – A wild elephant Aug 11 '15 at 15:38