Make a div 100% height of the browser window

2018-12-30 23:25发布

I have a layout with two columns - a left div and a right div.

The right div has a grey background-color, and I need it to expand vertically depending on the height of the user's browser window. Right now, the background-color ends at the last piece of content in that div.

I've tried height:100%, min-height:100%; etc.

30条回答
怪性笑人.
2楼-- · 2018-12-31 00:00

This is what worked for me:

<div style="position:fixed; top:0px; left:0px; bottom:0px; right:0px;"> </div>

Use position:fixed instead of position:absolute, that way even if you scroll down the division will expand to the end of the screen.

查看更多
骚的不知所云
3楼-- · 2018-12-31 00:01

Here's a fix for the height.

In your CSS use:

#your-object: height: 100vh;

For browser that don't support vh-units, use modernizr.

Add this script (to add detection for vh-units)

// https://github.com/Modernizr/Modernizr/issues/572
// Similar to http://jsfiddle.net/FWeinb/etnYC/
Modernizr.addTest('cssvhunit', function() {
    var bool;
    Modernizr.testStyles("#modernizr { height: 50vh; }", function(elem, rule) {   
        var height = parseInt(window.innerHeight/2,10),
            compStyle = parseInt((window.getComputedStyle ?
                      getComputedStyle(elem, null) :
                      elem.currentStyle)["height"],10);

        bool= !!(compStyle == height);
    });
    return bool;
});

Finally use this function to add the height of the viewport to #your-object if the browser doesn't support vh-units:

$(function() {
    if (!Modernizr.cssvhunit) {
        var windowH = $(window).height();
        $('#your-object').css({'height':($(window).height())+'px'});
    }
});
查看更多
笑指拈花
4楼-- · 2018-12-31 00:05

If you use position: absolute; and jQuery, you could use

$("#mydiv").css("height", $(document).height() + "px");
查看更多
素衣白纱
5楼-- · 2018-12-31 00:07

You need to do two things, one is to set the height to 100% which you already did. Second is set the position to absolute. That should do the trick.

html,
body {
  height: 100%;
  min-height: 100%;
  position: absolute;
}

Source

查看更多
几人难应
6楼-- · 2018-12-31 00:08

One of the options is using CSS table. It has great browser support, even works in IE8.

JSFiddle Example

html, body {
  height: 100%;
  margin: 0;
}
.container {
  display: table;
  width: 100%;
  height: 100%;
}
.left, .right {
  display: table-cell;
  width: 50%;
}
.right {
  background: grey;
}
<div class="container">
  <div class="left"></div>
  <div class="right"></div>
</div>

查看更多
几人难应
7楼-- · 2018-12-31 00:09

You can use the view-port unit in CSS :

HTML :

<div id="my-div">Hello World!</div>

CSS :

#my-div {
    height:100vh; /*vh stands for view-port height, 1vh is 1% of screen height*/
}
查看更多
登录 后发表回答