如何使网页高度适应屏幕高度?

33

我需要使我的网页高度适应屏幕尺寸,避免出现滚动条。

HTML

<body>
    <form id="form1" runat="server">
    <div id="main">
        <div id="content">

        </div>
        <div id="footer">

        </div>
    </div>
    </form>
</body>

CSS

#content{ background-color:#F3F3F3; margin:auto;width:70%;height:700px;}
#footer{width:100%;background-color:#666666;height:200px;}

可能是重复的问题:如何使 div 的高度占据整个浏览器窗口 - Jean-François Corbett
9个回答

29

一个快速、不优雅但有效的独立解决方案,使用内联CSS并且无需jQuery要求。据我所知,它从IE9开始就可以工作。

<body style="overflow:hidden; margin:0">
    <form id="form1" runat="server">
        <div id="main" style="background-color:red">
            <div id="content">

            </div>
            <div id="footer">

            </div>
        </div>
    </form>
    <script language="javascript">
        function autoResizeDiv()
        {
            document.getElementById('main').style.height = window.innerHeight +'px';
        }
        window.onresize = autoResizeDiv;
        autoResizeDiv();
    </script>
</body>

25

使用固定位置可以实现您所需的效果:

#main
{         
    position:fixed;
    top:0px;
    bottom:0px;
    left:0px;
    right:0px;
}

25

正如另一位用户在这里描述的那样,你只需要添加以下代码:

height: 100vh;

根据您需要填充屏幕的样式


5
不要给出具体的高度,而是使用相对高度,总和为100%。例如:
  #content {height: 80%;}
  #footer {height: 20%;}

添加

 html, body {height: 100%;}

绝对高度从哪里来?0的100%是0。你如何告诉它开始时什么是100%? - nckbrz
1
100%是视口的完整(当前)大小。因此,您不需要告诉它,浏览器实际上会自行确定100%的值。 - Bakabaka

0

尝试:

#content{ background-color:#F3F3F3; margin:auto;width:70%;height:77%;}
#footer{width:100%;background-color:#666666;height:22%;}

(77%和22%大致保持contentfooter的比例,不应导致滚动)


0

你可以使用 CSS 将 body 标签设置为以下样式:

body
{
padding:0px;
margin:0px;
width:100%;
height:100%;
}

0
使用这个,将你的类“home”替换为你自己的。
(function ($) {
    $(function(){"use strict";
        $('.home').css({'height':($(window).height())+'px'});
        $(window).resize(function(){
        $('.home').css({'height':($(window).height())+'px'});
        });
    });
  
  })(jQuery);

0

我使用了一个CSS解决方案,证明它非常灵活。

你需要选择一个元素作为全高度的元素。它还需要是每个内容块的父元素。这可以是<body>元素或DOM中的任何位置。

此外,你必须指定一个子元素来增长,以填充屏幕所需的任何空间。

.content-parent {
  min-height: 100vh;  /* Forces to always fill the screen vertically... */
  min-height: -webkit-fill-available;  /* ...except on mobile, when you want to stay within the chrome */
  display: flex;  /* Enable content to stretch... */
  flex-direction: column;  /* ...vertically */
}

.filler-child {
  flex-grow: 1;  /* Designates this element to stretch to fill */
}

示例HTML:

<html>
  <head>...</head>
  <body>
    <div class="parent">
      <div class="hero">...</div>
      <div class="content filler-child">...</div>
      <div class="footer">...</div>
    </div>
  </body>
</html>

0

请确保通过添加 important 来覆盖原始样式。

height: 100vh !important;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接