CSS 強大的威力

Ilmari Heikkinen

昨天在辦公室,我們提出了奇怪又神奇的 CSS 技巧。以這個情況為例,這個做法會讓空白連結顯得更加顯眼:

a[href = ""] {
    background: red;
    color: white;
    font-size: x-large;
}

查看 jsFiddle 的即時範例

此外,您還能設定絕對連結和相對連結的樣式:

a[href ^= http] {
    display: inline-block;
    color: red;
    transform: rotate(180deg);
}

查看 jsFiddle 的即時範例

如果您想針對指向網域外的連結採用不同樣式,可以使用 :not() 選取器。這就是我們在 HTML5Rocks 上擷取外部連結旁的小箭頭。

a[href ^= 'http']:not([href *= 'html5rocks.']) {
    background: transparent url(arrow.png) no-repeat center right;
    padding-right: 16px;
}

查看 jsFiddle 的即時範例

提醒你,你不一定要設定連結樣式,但可以按照下列步驟反轉所有 PNG 圖片:

img[src $= .png] {
    filter: invert(100%);
}

接下來介紹屬性選取器的部分,您知道可以同時顯示文件的標頭和其他元素嗎?

head {
    display: block;
    border-bottom: 5px solid red;
}
script, style, link {
    display: block;
    white-space: pre;
    font-family: monospace;
}

或者,您也可以運用 CSS 屬性函式的強大功能,填補內容中的 :after 和 :before 內容嗎?

script:before {
    content: "<script src=\"" attr(src) "\" type=\"" attr(type) "\">";
}
script:after {
    content: "</script>";
}

style:before {
    content: "<style type=\"" attr(type) "\">";
}
style:after {
    content: "< /style>";
}

/* And for a finish, <link> */
link:before {
    content: "<link rel=\"" attr(rel) "\" type=\"" attr(type) "\" href=\"" attr(href) "\" />";
}

查看 jsFiddle 的即時範例

請注意,attr() 會讀取相符元素的屬性值,因此若在 #foo:之前 使用,它會讀取 #foo 中的屬性。