CSS: 解决100% 高度失效 height 100% is not working when scrolling down page

原代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample</title>

    <style>
        html, body{
            padding: 0;
            margin: 0;
        }
        .heightShower  {
            width:30%;
            height: 100%;
            color: #fff;
            background-color: #e0f;
        }
    </style>
</head>
<body>
    <div class="heightShower">
        This is the element
    </div>
</body>
</html>

解决方案是:

/* 100% height fix */
html, body{  
    height: 100%;
}

修改后代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample</title>

    <style>
        /* 100% height fix */
        html, body{
            height: 100%;
            padding: 0;
            margin: 0;
        }
        .heightShower  {
            width:30%;
            height: 100%;
            color: #fff;
            background-color: #e0f;
        }
    </style>
</head>
<body>
    <div class="heightShower">
        This is the element
    </div>
</body>
</html>

Alternative

Or you could position .content as fixed and you’d have the same effect but with a different approach

.content {
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
}

如果页面存在滚动条的话, 可以用  min-height:100% 代替 height:100%

when it is a  scrolling down page, Try using min-height:100% instead of height:100%.

结果如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample</title>

    <style>
        /* 100% height fix */
        html, body{
            height: 100%;
            padding: 0;
            margin: 0;
        }
        .heightShower  {
            width:30%;
             /* 100% height fix for scrolling down page */
            min-height: 100%;
            color: #fff;
            background-color: #e0f;
        }
    </style>
</head>
<body>
    <div class="heightShower">
        This is the element
    </div>
</body>
</html>

当然,如果你想要让body的height保持100%,那么方法如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample</title>

    <style>
        html {
	    height: 100%;
	}

	body{
	    min-height: 100%;
	}
    </style>
</head>
<body>
 
</body>
</html>

关于 html和body在css中的区别,可以参考另一篇文章:CSS: HTML 和 Body 的区别

 

本文:  CSS: 100% 高度失效 height 100% is not working

Leave a Reply