CSS中height:100vh和height:100%的区别是什么?

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

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的区别差不多自己探索去吧

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: CSS