關(guān)于 CSS3
的box-sizing
屬性還可以參考W3school
box-sizing屬性的語(yǔ)法
和其他css屬性一樣遵馆,該屬性有三個(gè)可取的值,具體語(yǔ)法:
box-sizing: content-box|border-box|inherit;
以下案例都是基于固定寬高的容器為例庸蔼。
content-box(默認(rèn))
box-sizing
屬性的默認(rèn)值就是 content-box
产弹。
實(shí)例:
<ul class="box">
<li class="box-item content-box"></li>
<li class="box-item border-box"></li>
<li class="box-item inherit"></li>
</ul>
.box {
background: #737373;
height: 500px;
padding: 20px;
display: flex;
}
.box-item {
background: white;
list-style: none;
width: 350px; /*注意主届! 固定寬高*/
height: 350px;
margin: 40px auto;
}
.content-box {
box-sizing: content-box;
/*注意洲守! padding: 20px; */
/* border: 2px solid red; */
background: burlywood;
}
以上運(yùn)行結(jié)果為:
- 設(shè)置
padding
和border
之前 寬度和高度為350px
padding 和 border之前
設(shè)置padding
和border
之后 寬度和高度為394px
padding 和 border之后
總結(jié):
box-sizing
值為content-box
時(shí)候片酝,元素的padding
和border
屬性的值會(huì)在元素的寬度和高度屬性基礎(chǔ)上繪制元素的內(nèi)邊距和邊框
此時(shí)元素的寬度 = width + padding + border (高度同理)
border-box (重點(diǎn))
Element-UI
組件庫(kù)就大量的使用了 border-box
值细燎。
繼以上案例。針對(duì)第二的li
澳窑,調(diào)整其樣式為:
.border-box {
box-sizing: border-box;
border: 2px solid red;
padding: 20px;
background: darkorange;
}
border-box :padding 和 border之后
總結(jié):
設(shè)置為
border-box
值之后斧散,對(duì)元素設(shè)置內(nèi)邊距和邊框不會(huì)影響元素的寬高供常。也就是說(shuō)為元素指定的任何內(nèi)邊距和邊框都將在已設(shè)定的寬度和高度內(nèi)進(jìn)行繪制摊聋。
此時(shí)元素的寬度 = width (高度同理)
inherit
從父元素繼承 box-sizing
屬性的值,若未設(shè)置栈暇,默認(rèn)為 content-box
麻裁,在此就不贅述了。
完整代碼
<template>
<ul class="box">
<li class="box-item content-box"></li>
<li class="box-item border-box"></li>
<li class="box-item inherit"></li>
</ul>
</template>
<style scoped>
.box {
background: #737373;
height: 500px;
padding: 20px;
display: flex;
}
.box-item {
background: white;
list-style: none;
width: 350px;
height: 350px;
margin: 40px auto;
}
.content-box {
box-sizing: content-box;
padding: 20px;
border: 2px solid red;
background: burlywood;
}
.border-box {
box-sizing: border-box;
padding: 20px;
border: 2px solid red;
background: darkorange;
}
.inherit {
box-sizing: inherit;
}
</style>
以上就是 box-sizing
屬性的取值以及屬性值之間的區(qū)別。
對(duì)于固定寬高
的元素設(shè)置 box-sizing: border-box
之后煎源,再也不用擔(dān)心元素的寬高隨padding
變化了色迂。