元素高度自适应屏幕高度解决方案

<style>
			body,html {
				height: 100%;
			}
			.header {
				 100%;
				height: 30px;
				background: #f00;
			}

			.content {
        position: relative;
				height: 100%;
			}

			.content .left {
                                 300px;
				height: 100%;
				background: #ff0;
			}

			.content .right {
				position: absolute;
				left: 300px;
				top: 0;
				right: 0;
				background: #0f0;
				/*  100%; */
                                height: 100%;
			}
		</style>

  

               <header class="header">
			
		</header>
		<article class="content">
			<section class="left">
				
			</section> 
			<section class="right">

			</section>
			
		</article> 

  

一、js实现

body标签高度设置为100%,通过resize事件监听浏览器的大小改变,动态设置元素高度为body高度。

	<script>
		const contentHeight = document.querySelector('body').offsetHeight
		const leftEle = document.querySelector('.left')
		const rightEle = document.querySelector('.right')
		window.onresize=()=> {
                leftEle.style.height = contentHeight
			rightEle.style.height = contentHeight
		}
	</script>

  

二、css实现

calc计算高度,值得注意的是calc中运算符+/-两边必须留空格才能被解析为正确的表达式。

calc规则:

  • 除以零会导致HTML解析器生成错误。
  • +-运营商必须用空格包围。例如,calc(50% -8px)将被解析为百分比,后跟负长度 - 无效表达式 - 而calc(50% - 8px)百分比后跟减法运算符和长度。同样,calc(8px + -50%)将其视为长度,后跟加法运算符和负百分比。
  • */运营商不需要的空白,但增加它的一致性允许和建议。
  • 涉及自动和固定布局表中的表列,表列组,表行,表行组和表格单元格的宽度和高度百分比的数学表达式被视为auto已指定。
  • 允许嵌套calc()函数,在这种情况下,内部函数被视为简单的括号。
	.content {
              position: relative;
              height: calc(100% - 30px);
	      /* height: 100%; */
        }

to be continued...  

原文地址:https://www.cnblogs.com/yy95/p/9668380.html