CSS初學感受很簡單,但隨着學習的深刻才感受CSS的水由多深,日常總會遇到各類坑,先總結一些常常遇到的坑css
雖然咱們平時在寫CSS的時候都是用小寫,但其實CSS並非大小寫敏感的html
.test{ background-COLOR:#a00; width:100px; height: 100px; }
雖然把background-color寫爲了background-COLOR,但仍然會生效,之因此寫成小寫是由於xhtml標準的關係,可是即便不是xhtml仍是寫成小寫比較好,美觀、易讀並且能夠應對可能的轉換需求web
當兩個規則都做用到了同一個html元素上時,若是定義的屬性有衝突,那麼應該用誰的值的,CSS有一套優先級的定義。瀏覽器
不一樣級別網絡
同一級別less
同一級別中後寫的會覆蓋先寫的樣式學習
上面的級別仍是很容易看懂的,可是有時候有些規則是多個級別的組合,像這樣字體
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> div.test{ background-COLOR:#a00; width:100px; height: 100px; } .test.test2{ background-COLOR:#0e0; width:100px; height: 100px; } </style> </head> <body> <div class="test test2"></div> </body> </html>
到底div是應用那條規則呢,有個簡單的計算方法(經園友提示,權值實際並非按十進制,用數字表示只是說明思想,一萬個class也不如一個id權值高)url
咱們能夠把選擇器中規則對應作加法,比較權值,若是權值相同那就後面的覆蓋前面的了,div.class的權值是1+10=11,而.test1 .test2的權值是10+10=20,因此div會應用.test1 .test2變成綠色spa
並非全部的屬性對行內元素都可以生效
<div style=""> <span style="padding:4px; margin:8px; height: 500px; width:1000px; ">123456789123456789</span> </div> <div style=""> <span style="padding:4px; margin:8px; height: 500px; width:1000px; ">123456789</span> </div>
經過例子能夠看出,咱們對span設置的width和height屬性並無生效,margin-top和margin-bottom無效,padding-top和padding-bottom會改變元素範圍(背景區域變大了),但並無影響下面元素位置
咱們在寫字體的尺寸的時候經常使用的單位有
這些字體分別有什麼含義?
咱們知道:checked會選擇被選中的checkbox和radio,看個例子
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> :checked{ margin: 10px; } </style> </head> <body> <input id="t1" type="checkbox" checked/> <input id="t3" type="radio" checked/> <select> <option id="t2">test</option> <option id="t4">test2</option> </select> </body> </html>
對於前兩個margin變成10px咱們不奇怪,可是當咱們看select的option的時候會發現被選中的option的margin業變成了10px,沒有被選中的option則沒有變化!
是的:checked也會選擇被選中的option
咱們知道寫在頁面上的img標籤,不管顯示與否,圖片都會被加載(因此試圖經過對圖片display:none來達到節省網絡流量的作法就省省吧。。。),咱們也常用backgroung-image等css屬性爲頁面添加圖片,這些圖片是否是必定會被加載呢,看個例子
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> .useless{ background-image: url(images/0.jpg); } .hidden{ background-image: url(images/1.jpg); } .none{ background-image: url(images/2.jpg); } .parentHidden{ background-image: url(images/3.jpg); } .parentNone{ background-image: url(images/4.jpg); } </style> </head> <body> <div class="hidden"></div> <div class="none"></div> <div style="visibility:hidden;"> <div class="parentHidden"></div> </div> <div style="display:none;"> <div class="parentNone"></div> </div> <div style="display:none"> <img src="images/5.jpg"></div> </body> </html>
看一下網絡監視狀況(怎麼柳巖的照片變小後感受怪怪的。。。)
咱們能夠發現圖片0和4沒有被下載,0是沒有用到的CSS,4是父容器的display被設爲none的狀況,這兩種狀況下的CSS引用的圖片是不會被加載的,而父容器設置visibility屬性爲hidden仍然會加載圖片,不要搞混了