位置: IT常识 - 正文
推荐整理分享CSS中height:100vh和height:100%的区别是什么?(css width height),希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:css height,css height vh,cssheight100%无效,css height100%,cssheight100%无效,css height,css height100%,css height,内容如对您有帮助,希望把文章链接给更多的朋友!
首先,我们得知道1vh它表示的是当前屏幕可见高度的1/100,而1%它表示的是父元素长或者宽的1%(可以这么理解?)
1、对于设置height:100%;有下面几种情况:
(1)当父元素固定高度,子元素设置height:100%;时
<style> #father1 { width: 300px; height: 300px; background-color: yellow; margin: 20px; } #son1{ height: 100%; background-color: blue; }</style><div id="father1"> <div id="son1"></div></div>结果如下: 子元素会自动填充父元素,也就是此时子元素的高度等于父元素的高度,同时我们可以知道,当父元素的宽高为0时,子元素的高度也为0,那么整个图形也就变成下面这个样了
(2)当一个元素内部没有子元素的时候,设置height:100%;width:100%;,此时该元素高度为0。
(3)当一个元素内部有固定高度子元素的时候,给这个元素设置height:100%;width:100%;,那么这个元素自动被子元素高度撑开,例如:
<style> #father1 { width: 100%; background-color: yellow; margin: 20px; } #son1{ width: 100px; height: 100px; background-color: blue; }</style><div id="father1"> <div id="son1"></div></div>结果如下:
可以看到,父元素是被子元素撑开了,此时父元素的高度就等于子元素的高度。
2、对于设置height:100vh时有如下的情况:
一个元素设置height:100vh,那么该元素会被撑开与屏幕高度一致。
(1)即便父元素限制了宽高,只要子元素设置height:100vh,那么子元素的高度就会和屏幕一样高
<style> #father1 { width: 300px; height: 300px; background-color: yellow; margin: 20px; } #son1 { height: 100vh; background-color: blue; }</style><div id="father1"> <div id="son1"></div></div>结果如下:
可以看到,子元素设置height:100vh时,不会被父元素的高度所限制
height:100vh == height:100%;
(2)父元素设置height:100vh,能够保证元素无论是否有没有内容,高度都等于屏幕高度。
<style> #father1 { width: 300px; height: 100vh; background-color: yellow; margin: 20px; } #son1 { height: 300px; background-color: blue; }</style><div id="father1"> <div id="son1"></div></div>结果如下:
同样的,width:100%和width:100vw的区别差不多,自己探索去吧
再补充下iwidth:100%和width:auto的区别
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .outer { height: 200px; border: 1px solid red; } .center { display: inline-block; height: 100%; width: 100%; border: 1px solid green; } .inner { height: 50px; width: 500px; border: 1px solid blue; } </style> </head> <body> <div class="outer"> <div class="center"> <div class="inner"></div> </div> </div> <script></script> </body></html>如果当前是元素设置了width/height:100%,那么对齐父元素内容区域的宽高; 如果当前元素设置了width/height:auto;那么对齐子元素内部元素的宽高
上一篇:【今日清明节】 (© Xinhua/Alamy Stock Photo)(今日清明是清明开始还是结束)
友情链接: 武汉网站建设