CSS3 Selector

2015/12/16 阮韞澂

Form Selector

  • :checked
  • :enabled
  • :disabled
  • :valid
  • :invalid
  • :required
  • :optional
  • :read-only
  • :read-write
  • :in-range
  • :out-of-range

:checked

被選擇的目標

可用於radio,checkbox,<option>


input:checked{
    width:2em;
    height:2em;
}
select :checked{
    background:red;
}
						
Demo

:enabled & :disabled

判斷是否有disabled屬性

可用於任意元素


:enabled{
    background:lightgreen;
}
:disabled{
    background:red;
}
						
Demo

:valid & :invalid

判斷是否符合驗證規則

沒有驗證功能的元素為invalid

IE10以下不支援


input:valid{
    background:yellow;
}
input:invalid{
    background:red;
}
						
Demo

:required & :optional

判斷是否有required屬性

只作用於表單元素

IE10以下不支援


:required{
    background:yellow;
}
:optional{
    background:red;
}
						
Demo

:read-only & :read-write

判斷是否有readonly屬性

IE不支援,Firefox要加-moz-

可用於任意元素


:-moz-read-only{
    background:yellow;
}
:read-only{
    background:yellow;
}
:-moz-read-write{
    background:red;
}
:read-write{
    background:red;
}
						
Demo

:in-range & :out-of-range

判斷值是否在指定的區間內

只能用於可指定區間的元素

區間未指定則認定in-range

IE不支援


:in-range{
    background:yellow;
}
:out-of-range{
    background:red;
}
						
Demo

Try It!

以FormSelectors裝飾網頁中的表單

:target

被選取的錨點


p:target{
    background:yellow;
}
						
Demo

CSS Pages


.pages section{
    border:1px solid gray;
    position:absolute;
    top:1em;
    left:0;
    width:500px;
    height:300px;
    background:#CCCCCC;
}
.pages section:target{
    z-index:1;
}
						
Demo

Try It!

在網頁中以CSS達成分頁效果

Pseudo-Elements

  • ::pseudo-element
  • 元素的一部份但不存在與程式碼中
  • 理論上與Tag選擇器同級
  • 與其他選擇器的互動不太正常...

::selection

被框選的部分

只有color,background,outline,cursor可以使用

Firefox要加-moz-


::-moz-selection{
    background:yellow;
    color:red;
}
::selection{
    background:yellow;
    color:red;
}
					
Demo

::first-line

文字中第一行

只有部分屬性可使用

一定是block


::first-line{
    background:yellow;
}
					
Demo

::first-letter

一段文字中的第一個字

只有部分屬性可使用

一定是block


::first-letter{
    background:yellow;
    font-size:2em;
}
					
Demo

Pseudo-Elements Relation

first-letter>first-line>selection

若選擇包含完整first-line則selection優先

Firefox:selection>first-letter>first-line

IE:selection&first-letter>first-line
selection與first-letter同時作用則使selection恢復預設值

Demo

Try It!

以Pseudo-Elements裝飾網頁中的文字段落

::before & ::after

元素前後的空白

搭配content屬性使用

常用於排版、繪圖等

CSS content


content:normal|none|attr()|url()|("text")|counter|open-quote|close-quote|no-open-quote|no-close-quote
						
  • normal為none,預設值
  • attr()為所屬於元素之HTML屬性
  • url()為一個物件的路徑(圖片、影片、音訊等)
  • "text"為指定之文字
  • counter為計數器,從1開始
  • 可以多個值

::before & ::after

Demo

Try It!

  1. 以::after提示超連結的目標Demo
  2. 以::before與::after將一個div裝飾為多重邊框

多重邊框進階版-boxshadow

Demo