css设置高度100%(CSS中height:100vh和height:100%的区别是什么?)
CSS中height:100vh和height:100%的区别
首先 ,我们得知道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;那么对齐子元素内部元素的宽高创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!