Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

css - CSS2 Attribute Selectors with Regex

CSS Attribute selectors allow the selection of elements based on attribute values. Unfortunately, I've not used them in years (mainly because they're not supported by all modern browsers). However, I remember distinctly that I was able to use them to adorn all external links with an icon, by using a code similar to the following:

a[href=http] {
    background: url(external-uri);
    padding-left: 12px;
}

The above code doesn't work. My question is: How does it work? How do I select all <a> tags whose href attribute starts with "http"? The official CSS spec (linked above) doesn't even mention that this is possible. But I do remember doing this.

(Note: The obvious solution would be to use class attributes for distinction. I want to avoid this because I have little influence of the way the HTML code is built. All I can edit is the CSS code.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As for CSS 2.1, see http://www.w3.org/TR/CSS21/selector.html#attribute-selectors

Executive summary:

    Attribute selectors may match in four ways:

    [att]
    Match when the element sets the "att" attribute, whatever the value of the attribute.
    [att=val]
    Match when the element's "att" attribute value is exactly "val".
    [att~=val]
    Match when the element's "att" attribute value is a space-separated list of
    "words", one of which is exactly "val". If this selector is used, the words in the 
    value must not contain spaces (since they are separated by spaces).
    [att|=val]
    Match when the element's "att" attribute value is a hyphen-separated list of
    "words", beginning with "val". The match always starts at the beginning of the
    attribute value. This is primarily intended to allow language subcode matches
    (e.g., the "lang" attribute in HTML) as described in RFC 3066 ([RFC3066]).

CSS3 also defines a list of selectors, but the compatibility varies hugely.

There's also a nifty test suite that that shows which selectors work in your browser.

As for your example,

a[href^=http]
{
    background: url(external-uri);
    padding-left: 12px;
}

should do the trick. Unfortunately, it is not supported by IE.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...