標籤:
css-盒子模型
一、padding(內邊距)
元素的內邊距在邊框和內容區之間。控制該地區最簡單的屬性是 padding 屬性。CSS padding 屬性定義元素邊框與元素內容之間的空白地區。
padding-left/right/top/bottom 左內邊距/右內邊距/上內邊距/下內邊距
例如:h1 {
padding-top: 10px;
padding-right: 0.25em;
padding-bottom: 2ex;
padding-left: 20%;
}
可以單獨使用控制單獨一邊的效果,當然也可以合并一起使用
例如:
padding:2px 3px 4px 5px; /*上內邊距2px 右內邊距3px 下內邊距4px 左內邊距5px*/
padding:2px 3px 4px; /*上內邊距2px 右/左內邊距3px 下內邊距4px*/
padding:2px 3px; /*上/下內邊距2px 右/左內邊距3px*/
padding:2px; /*上右下左內邊距都為2px*/
二、border(邊框)
在 HTML 中,我們使用表格來建立文本周圍的邊框,但是通過使用 CSS 邊框屬性,我們可以建立出效果出色的邊框,並且可以應用於任何元素。元素外邊距內就是元素的的邊框 (border)。元素的邊框就是圍繞元素內容和內邊據的一條或多條線。
1、border-left/right/top/bottom(與padding類似)
2、border-style(邊框樣式)
border-left/right/top/bottom-style
例如:border-style:dotted solid double dashed;
/*上邊框是點狀 右邊框是實線 下邊框是雙線 左邊框是虛線*/
具體樣式:
none /*無效果,預設*/
solid /*實線*/
double /*雙實線*/
dotted /*點狀*/
dashed /*虛線*/
groove /* 3D 凹槽邊框*/
ridge /*3D 壟狀邊框*/
inset /*3D inset 邊框*/
outset /*outset 邊框*/
inherit /*規定應該從父元素繼承邊框樣式*/
3、border-color(邊框顏色)
border-left/right/top/bottom-color
例如:p {
border-style: solid;
border-color: blue rgb(25%,35%,45%) #909090 red;
}
4、border-width(邊框寬度)
border-left/right/top/bottom-width
例如:p {
border-style: solid; border-width: 15px 5px 15px 5px;
}
5、border-radius(邊框半徑,可繪製圓角邊框)
例如:div{
border:2px solid;
border-radius:25px 50px 75px 100px;
-moz-border-radius:25px 50px 75px 100px; /* Old Firefox */
}
與border的其他屬性相似,它也是可以作用在四個角上的(左上,右上,右下,左下)
6、box-shadow (邊框陰影)
例如:div{box-shadow: 10px 10px 5px red;}
表示:水平方向的距離10px(正值:陰影在右邊) /*可以為負值,負值則表示陰影在左邊*/
豎直方向的距離10px(正值:陰影在左邊) /*可以為負值,負值則表示陰影在上面*/
模糊度5px
陰影顏色red
7、border-image(邊框圖)
border-image-sourcesource: url(xx.png)
border-image-width:邊框寬/九宮格格寬
border-image-repeat: stretch(展開)/repeat(重複)/round(平鋪)
當然也可以將這三種方式合并在一起,例如:
div{
border: 20px solid transparent;
border-image:url(box.png) 20 round; /*注意:此種寫法width的值不能帶單位*/
/*-webkit-border-image:url(box.png) 20 round;*/
}
三、margin(外邊距)
margin-left/right/top/bottom(與padding類似)
(略)
四、補充
outline(輪廓)
outline-color || outline-style || outline-width
該屬性是複合屬性,且不佔頁面空間,用法如下:
img { outline-color: orange; outline-style: solid ; outline-width: medium ; }
五、綜合
1、一個區塊元素所佔的空間總大小:
X軸:margin-left + border-left + padding-left + width + padding-right + border-right + margin-right
同理,Y軸:margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom
2、區塊元素合并
無浮動
豎直方向上排布,相鄰元素的Margin會合并,合并後的值是二者指定的間距中的較大值,Padding各自獨立;
當一個元素包含在另一個元素中時(假設沒有內邊距或邊框把外邊距分隔開),它們的上和/或下外邊距也會發生合并。請看:
假設有一個空元素,它有外邊距,但是沒有邊框或填充。在這種情況下,上外邊距與下外邊距就碰到了一起,它們會發生合并:
如果這個外邊距遇到另一個元素的外邊距,它還會發生合并:
有浮動
padding各自獨立;
豎直/水平方向Margin上都各自獨立
3、內嵌元素合并
內嵌元素:水平方向上排布,一行不夠自動排布到下一行,
Margin:水平方向上各自獨立,不合并;豎直方向上無效。
Padding:水平方向上各自獨立;豎直方向上有效但不佔用頁面空間(即上下兩行的padding可能會重疊)
六、其他:
(1)outline、box-shadow不會佔用頁面空間,故也不計入盒子模型的計算。
(2)float會對間距的合并產生影響
(3)區塊若想在父元素中水平置中,margin: 0 auto; 由瀏覽器自動計算左右間距——平均分配
(4)為了屏蔽瀏覽器預設值造成的相容性問題,頁面配置時可以添加 *{margin:0; padding:0}
css-盒子模型