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 attr-function 的强大功能来填充 :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:before,则它将从 #foo 读取属性。