1. 程式人生 > 實用技巧 >css規範、行高、三大特性、背景、盒子模型

css規範、行高、三大特性、背景、盒子模型

CSS書寫規範

空格規範

選擇器{}之間必須包含空格

示例 : .selector{}

屬性名與之後的 : 之間不允許包含空格,:屬性值之間必須包含空格

示例: font-size: 12px;

選擇器規範

當一個rule包含多個selector時,每個選擇器申明必須獨佔一行

選擇器的巢狀層級儘量不大於 3 級,位置靠後的限定條件應儘可能精確

示例:

/* good */
.post,
.page,
.comment {
line-height: 1.5;
}

屬性規範

屬性定義必須另起一行

示例

.selector {
margin: 0;
padding: 0;
}

行高(line-height)

用的比較多的地方是讓一個文字在盒子裡垂直居中

line-height分為:上邊距,下邊距,內容高度

line-height會自動平分上邊距,下邊距,從而使內容高度垂直居中

如果line-height等於height,則文字會垂直居中

如果line-height大於height,則文字會垂直偏下

如果line-height小於height,則文字會垂直偏上

CSS三大特性

css層疊性

一般情況下,如果出現樣式衝突,則會按照CSS書寫的順序,以最後的樣式為準

樣式不衝突,不會層疊

css繼承性

子標籤會繼承父標籤的某些樣式,如文字顏色和字號

css優先順序

選擇器權重
選擇器權重
繼承 或者 * 0, 0, 0, 0
標籤選擇器 0, 0, 0, 1
類 / 偽類 0, 0, 1, 0
id 0, 1, 0, 0
行內樣式 1, 0, 0, 0
!import ∞無窮大
權重可以重疊

位數之間沒有進位制

0,0,0,5 + 0,0,0,5 =0,0,0,10

div ul  li  ------>    0,0,0,3

.nav ul li ------> 0,0,1,2

a:hover -----—> 0,0,1,1

.nav a ------> 0,0,1,1

#nav p -----> 0,1,0,1

CSS背景(background)

background-color背景顏色屬性
background-image 背景圖片地址
background-repeat 是否平鋪
background-position 背景位置
background-attachment 背景固定還是滾動 fixed(背景固定)
背景的合寫(複合屬性)
background:背景顏色 背景圖片地址 背景平鋪 背景滾動 背景位置
案例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        div {
            width: 500px;
            height: 500px;
            background-color: purple;
            background-image: url(images/l.jpg);
            background-repeat: no-repeat; /*不平鋪*/
            /*background-position: x  y ;*/
            /*background-position: left;  top 上  bottom 下  left  左  right  右 */
            background-position:  10px center;
             background-attachment: fixed;  /*fixed 固定的*/
            
            /*background:背景顏色 背景圖片地址 背景平鋪 背景滾動 背景位置*/
             background: #000 url(images/sm.jpg) no-repeat fixed  center top ;
        }
    </style>
</head>
<body>
    <div>
    </div>
</body>
</html>

背景透明(css3特性)

背景半透明之是指盒子背景半透明

盒子裡面的內容不受影響

background: rgba(0,0,0,0.3);

透明度的引數範圍:`0 - 1

盒子模型

盒子邊框(border)
border-style(邊框樣式)

屬性

none:不顯示邊框

solid:實線

dashed:虛線

border-collapse(細線邊框)

border-collapse:collapse

表示相鄰邊框合併在一起

padding(內邊距)

用於設定內邊距。是盒子邊框與盒子內容之間的距離

padding會撐開盒子

padding會撐開帶有width和height的盒子

解決方案:

改寬高

盒子佈局穩定性比較

width > padding > margin

border-radius圓角

border-radius的大小改為寬和高的一半就會成為一個標準的圓

div{
width: 300px;
height: 300px;
background-color: pink;
border-radius: 150px;
}

也可以分別控制4個角

border-radius: 1px 1px 1px 1px

box-shadow(盒子陰影)

語法格式

box-shadow:水平陰影 垂直陰影 模糊距離 陰影尺寸 陰影顏色 內/外陰影;

h-shadow

必須。水平陰影的位置。允許負值

v-shadow

必須。垂直陰影的位置。允許負值

blur

可選。模糊距離

spread

可選。陰影的尺寸

color

可選。陰影的顏色

inset

可選。將外部陰影(outset)改為內部陰影