刨根问底:CSS属性里的百分比到底是以什么为参考值?

1,878 阅读3分钟

这是我参与更文挑战的第16天,活动详情查看: 更文挑战 !

👽 概论

百分比是CSS中的一种常见属性值,width/height/margin/padding等一众属性都可使用%作为值,但你是否能清晰地说出各种属性在使用%时,其所参照的依据是什么吗?下面我们就来分类总结一下吧!

👽 分类介绍

👻 第一类:父子相同类

🙋子元素中的百分比,参照父元素相应属性的值,这类表现也是最容易理解、最为常见的一类。比如,子元素设置width:100%,即代表子元素的width为父元素width的100%。

🙋属于该类的属性有widthheight

🙋示例代码:

  <body>
    <div class="outerBox">
      <div class="innerBox"></div>
    </div>
  </body>
.outerBox {
  width: 400px;
  height: 400px;
  border: 2px solid red;
  background-color: red;
  background-clip: content-box;
}
.innerBox {
  width: 50%;
  height: 50%;
  border: 2px solid black;
  background-color: black;
  background-clip: content-box;
}

🙋 表现如图:

整体图:

image.png

父元素: image.png 子元素: image.png

🙋 🙋 🙋 额外思考:

那么问题来了,当上一例子中outer的width未设置时,子元素width:50%的值是多少呢?outer的height未设置时子元素height:50%又如何呢?

👻 第二类:父子相似类

🙋 对这类属性设置百分比时,水平方向上参照的对象是父元素的width,垂直方向上参照的是父元素的height。比如,子元素中设置max-width:100%min-height:100%即代表子元素的max-widthmin-height为分别为父元素width的100%、height的100%。

🙋属于该类的属性有max-widthmax-heightmin-widthmin-heighttopbottomleftreight

🙋示例代码:

.outerBox {
  width: 400px;
  height: 400px;
  max-width: 800px;
  min-height: 200px;
  border: 2px solid red;
  background-color: red;
  background-clip: content-box;
}
.innerBox {
  max-width: 50%;
  min-height: 50%;
  border: 2px solid black;
  background-color: black;
  background-clip: content-box;
}

🙋 表现如图:

整体图:

image.png

父元素: image.png 子元素: image.png

👻 第三类:只看父元素width的类

🙋 对这类属性设置百分比时,其参照的对象永远是父元素的width。比如,子元素中设置padding-left:100%margin-top:100%即代表子元素的padding-leftmargin-top为父元素width的100%。

🙋属于该类的属性有各类margin、各类padding

🙋示例代码:

.outerBox {
  width: 400px;
  height: 400px;
  margin-left: 0;
  padding-top:0;
  border: 2px solid red;
  background-color: red;
  background-clip: content-box;
}
.innerBox {
  width: 50%;
  height: 50%;
  margin-left: 50%;
  padding-top: 50%;
  border: 2px solid black;
  background-color: black;
  background-clip: content-box;
}

🙋 表现如图:

整体图:

image.png

父元素: image.png 子元素: image.png

👻 第四种,只看自身的类

🙋 这类属性的百分比值与以上最大的不同,就在于参考的不再是父元素,而是自身(水平方向上看width,垂直方向上看height)。

🙋属于该类的属性有border-radius

🙋示例代码:

.outerBox {
  width: 400px;
  height: 400px;
  border-radius: 0%;
  border: 2px solid red;
  background-color: red;
  background-clip: content-box;
}
.innerBox {
  width: 100px;
  height: 50px;
  border-radius: 50%;
  border: 2px solid black;
  background-color: black;
  background-clip: content-box;
}

🙋 表现如图:

整体图:

image.png

父元素: image.png 子元素: image.png

🙋 🙋 🙋 额外思考:

border-width设置百分比会如何呢?