Setting 100% height on an absolutely positioned el

2019-03-26 01:30发布

问题:

So after reading Stack Overflow and the web, I've gathered that there are two main tricks to achieving 100% height:

  1. Set height:100% on both the HTML and BODY
  2. Set your element to have either:
    • height:100%, or
    • top:0, bottom:0, position:absolute

However, even with those tricks I'm having difficulty setting the height of an absolutely positioned DIV to a true 100%. I can get 100% of the viewport size, but if the user scrolls down at all it becomes apparent that the div doesn't truly have 100% height.

I've made a simple JS Fiddle of the situation here: http://jsfiddle.net/9FEne/

My question is: does anyone know any further tricks to get a true (ie. content-height, not viewport-height) 100% height absolutely positioned div?

回答1:

Sorry, I missed the real question before and thought you wanted the window filled. If the issue is that the contents are longer than the window then what you need is to add position:relative to the body. http://jsfiddle.net/9FEne/7/

What is happening is that when you absolutely position something it positions (and sizes) relative to the nearest positioned element. If you don't tell it to position to the body then it will position to the window.



回答2:

You can use jQuery to achieve this trick

var h = $(window).height();
$('#yourdiv').height(h);


回答3:

I would use javascript to assign the height and width equal to document's height and window's width respectively; I've modified your jsfiddle to demonstrate it here:

http://jsfiddle.net/9FEne/1/