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: 10%;
    margin-left: 10%;
}
<div id="box">
    <div></div>
</div>
$(function() {
    console.log($('#box>div').css('paddingLeft'));//50px
    console.log($('#box>div').css('marginLeft'));//50px
})

4.line-height百分比

line-height設置百分比是基於當前字體大小

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM