css 样式的百分比

1.子元素宽度百分比指的是基于父级元素的width,不包含padding,border。

.box {
    width: 400px;
    height: 400px;
    padding: 20px;
    background-color: red;
}

.item {
    width: 100%;
    height: 200px;
    background-color: blue;
}
<div class="box">
    <div class="item">item元素的width为400px</div>
</div>

如果父级元素box-sizing: border-box,子级元素大小的百分比基于父级真正的大小,即除去padding,border之后的大小

.box {
    width: 400px;
    height: 400px;
    padding: 20px;
    background-color: red;
    box-sizing: border-box;
}

.item {
    width: 100%;
    height: 200px;
    background-color: blue;
}
<div class="box">
    <div class="item">父级box的宽度被padding占用40px,item元素的宽度只剩360px</div>
</div>

2.定位元素的宽高百分比:子级定位元素的宽高100%=父级定位元素width+padding的大小

注意的是:这里继承的并非是直接的父元素,而是父级定位元素,如果直接父元素没有定位 ,则继续查找更上一级的父元素,直到找到有定位的父元素或者body为止

.box {
    width: 400px;
    height: 400px;
    padding: 20px;
    background-color: red;
    position: relative;
    border: 10px solid #ccc;
    margin: 50px;
}

.item {
    width: 100%;
    height: 200px;
    background-color: blue;
    position: absolute;
    top:0;
    left:0;
}
<div class="box">
    <div class="item">item元素的width=440,刚好是box元素width+左右paading的大小</div>
</div>

3.padding和margin百分比

都是基于父元素的宽度

#box{
    width: 500px;
}
#box > div{
    width: 300px;
    padding-left: 20%;
}
<div id="box">
    <div></div>
</div>
$(function() {
    console.log($('#box>div').css('paddingLeft'));//100px
    console.log($('#box>div').css('marginLeft'));//100px
})

4.line-height百分比

line-height设置百分比是基于当前字体大小

#box{
    font-size: 20px;
    line-height: 100%;
}

<div  id="box"></div>
$(function(){      
    console.log($('#box').css('lineHeight'));//20px
})

猜你喜欢

转载自www.cnblogs.com/OrochiZ-/p/11565349.html