+ -

css如何让高度自适应

时间:2021-08-09

来源:互联网

在手机上看
手机扫描阅读

今天PHP爱好者给大家带来css让高度自适应的方法:1、给html元素设置“height:100%;display:table;”样式,给body元素设置“display:table-cell;height:100%;”样式即可。2、使用flex布局。希望对大家有所帮助。

本教程操作环境:windows7系统、CSS3&&HTML5版、Dell G3电脑。

在写css静态页面的时候让Html的高度自适应屏幕高度是一个常见的需求,比如你有一个需要置底的bottom按钮,需要在内容不足一屏的时候显示在屏幕的底部,在内容超过一屏的时候显示在所有内容的底部。

效果图:

这里写图片描述

CSS的做法

方法1:

html {
 height: 100%;
 display: table;
}

body {
 display: table-cell;
 height: 100%;
}

方法2:使用flex布局:

<p class="container">
 <header></header>
 <content></content>
 <footer></footer>
</p>

.container {
 display: flex;
 min-height: 100vh;
 flex-direction: column;
}

header {
 background: #cecece;
 min-height: 100px;
}

content {
 background: #bbbbbb;
 flex: 1; /* 1 代表盡可能最大,會自動填滿除了 header footer 以外的空間 */
}

footer {
 background: #333333;
 min-height: 100px;
}

JS的做法

css的做法有时候会在定位的时候造成一些麻烦,可以尝试使用js去动态改变html的高度

基于zepto

$(document).ready(function(){
 var windowHeight = $(window).height();
 if($(this).height() < windowHeight){
     $(this).height(windowHeight);
 }
});

原生js

window.onload = function(){
 var winHeight = 0;
 if (window.innerHeight){
   winHeight = window.innerHeight;
 }else if ((document.body) && (document.body.clientHeight)){
   winHeight = document.body.clientHeight;
 }
 var html = document.getElementsByTagName('html')[0];
 if(document.body.offsetHeight < windowHeight){
     html.style.height = windowHeight;
 }
};

以上就是css如何让高度自适应的详细内容,更多请关注php爱好者其它相关文章!