Appearance
宽高(100%、auto)
在 margin、padding 的时候我们对于 margin、padding 的百分比单位主要分为两种情况进行比较:
普通元素
绝对定位元素
百分比单位
普通元素
html
<div class="box" style="background-color: #eee;height: 1000px; width: 1000px; color: #fff;">
<div class="box" style="background-color: red;height: 700px; width: 700px; margin: 100px;padding: 100px;">
<div style="background-color: green;height: 10%;; width: 10%;">block</div>
<div style="background-color: green;height: 10%;; width: 10%;">block-m</div>
<div style="background-color: green;height: 10%;; width: 10%;display: inline; ">inline</div>
<div style="background-color: green;height: 10%;; width: 10%;display: inline;">inline-m</div>
<div style="background-color: green;height: 10%;; width: 10%; display: inline-block;;">inline-block</div>
<div style="background-color: green;height: 10%;; width: 10%; float: left;">float</div>
<div style="background-color: green;height: 10%;; width: 10%; float: left;">float-margin</div>
<div style="background-color: green;height: 10%;; width: 10%; position: relative;">position</div>
<div style="background-color: green;height: 10%;; width: 10%; position: relative;">position-margin</div>
</div>
</div>
效果如下:
结论
width、height 的百分比单位在普通元素上也是相对于父元素的<font class="j-font-red j-font-blod">content</font>
的宽高的
绝对定位元素
html
<!-- 绝对定位元素的百分比单位 -->
<div
class="pp-container"
style="display: inline-block;position:relative;background-color: #eee;height: 500px; width: 500px; color: #fff;"
>
<!-- box的宽高为 18px, box-size: border-box; 所以 p-container的 content : 160px padding: 10 * 2 border : 10 * 2 , -->
<!-- 那么绝对定位元素的width|height百分比单位 是相对于第一个定位祖先元素(content+padding)进行计算的-->
<div
class="p-container"
style="display: inline-block;position:relative;background-color: red;height: 200px; width: 200px; color: #fff; padding : 10px;border:10px #eee solid;box-sizing: border-box;"
>
<div style="display: inline-block;background-color: blue;height: 100px; width: 100px; color: #fff;">
<div class="box" style="position:absolute;background-color: green;height: 10%; width: 10%; color: #fff;">
position
</div>
</div>
</div>
<!-- box的宽高为 22px -->
<!-- box-size: content-box; 所以 p-container的 content : 200px padding: 10 * 2 border : 10 * 2 , -->
<!-- 那么绝对定位元素的width|height百分比单位 是相对于第一个定位祖先元素(content+padding)进行计算的-->
<div
class="p-container"
style="display: inline-block;position:relative;background-color: red;height: 200px; width: 200px; color: #fff; padding : 10px;border:10px #eee solid;box-sizing: content-box;"
>
<div style="display: inline-block;background-color: blue;height: 100px; width: 100px; color: #fff;">
<div class="box" style="position:absolute;background-color: green;height: 10%; width: 10%; color: #fff;">
position
</div>
</div>
</div>
</div>
效果如下:
结论
width、height 的百分比单位在绝对定位元素上也是相对于第一个定位祖先元素的<font class="j-font-red j-font-blod">content + padding</font>
的宽高的
100%
我们知道在普通元素上是相对于父元素的 content 的宽度、高度;在绝对定位元素上是相对于第一个定位祖先元素(content+padding)进行计算的。
所以为什么我们有些时候会发现width:100%
会导致出现水平滚动条的