Pergunta

Seletores de atributos CSS permitir a seleção de elementos com base em valores de atributos.Infelizmente, não os uso há anos (principalmente porque não são suportados por todos os navegadores modernos).Porém, lembro claramente que consegui usá-los para adornar todos os links externos com um ícone, usando um código semelhante ao seguinte:

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

O código acima não funciona.Minha pergunta é: Como funciona? Como faço para selecionar tudo <a> tags cujas href atributo começa com "http"?A especificação CSS oficial (link acima) nem menciona que isso é possível.Mas eu me lembro de fazer isso.

(Observação:A solução óbvia seria usar class atributos para distinção.Quero evitar isso porque tenho pouca influência na forma como o código HTML é construído.Tudo o que posso editar é o código CSS.)

Foi útil?

Solução

Quanto ao CSS 2.1, consulte http://www.w3.org/TR/CSS21/selector.html#attribute-selectors

Sumário executivo:

    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 também define uma lista de seletores, mas a compatibilidade varia enormemente.

Há também um conjunto de testes bacana isso mostra quais seletores funcionam no seu navegador.

Quanto ao seu exemplo,

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

deve fazer o truque.Infelizmente, não é suportado pelo IE.

Outras dicas

A resposta de Antti é suficiente para selecionar âncoras cujos hrefs começam com http e fornece um resumo perfeito do CSS2 disponível estilo regex seletores de atributos, assim:

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]).

No entanto, aqui está a maneira apropriada e ATUALIZADA de selecionar todos os links de saída usando o novo CSS3 :não seletor de pseudo classe assim como o novo *= sintaxe de substring para garantir que ele desconsidere quaisquer links internos que ainda possam começar com http:

a[href^=http]:not([href*="yourdomain.com"])
{
    background: url(external-uri);
    padding-left: 12px;
}

*Observe que isso não é compatível com o IE, pelo menos até o IE8.Obrigado, ou seja, você é o melhor: P

Observe que, no exemplo de Antti, você provavelmente desejaria adicionar uma captura para quaisquer links absolutos que possa ter para seu próprio domínio, o que provavelmente você não deseja sinalizar como 'externo', por exemplo:

a[href^="http://your.domain.com"]
{
    background: none;
    padding: 0;
}

E você iria querer isso depois a declaração anterior.

Você também pode incluir o prefixo completo do protocolo, caso tenha um documento local chamado "http-info.html" ao qual deseja vincular, por exemplo:

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

Observe que, em ambos os casos um pouco mais complexos, você deve citar o valor.Isso funciona, para mim, no IE7.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top