是否可以使用CSS单独将“外部”HTML链接设置为“相对”链接?

时间:2014-11-12 23:54:38

标签: html css

网站通常会设置链接,使网站中的用户与离开网站的用户保持不同。例如:

enter image description here

在上面,“网址”链接将用户引导到网址上的维基百科页面,而“stackoverflow.com”链接将用户引导到我们熟悉和喜爱的网站。

但是,维基百科样式表包含一个.external类来添加外部链接图标。

我已经涉及了一些CSS属性选择器a[href='??'],但即使仅使用相对内部链接也无法完全正确。

如果我们假设所有内部链接都是相对的,那么仅使用纯CSS可以设置内部和外部链接的样式吗?

此外,如果我们知道当前网站的地址,是否仍然可以完成?

4 个答案:

答案 0 :(得分:10)

除了 showdev 的答案之外,我相信以下是适用于当今浏览器的最准确的选择器:

a[href*='//']{
    /* ... */
}

这会处理不同的协议(请考虑http:// vs https://)。

请注意,要实现此目的,您必须为所有本地链接使用相对网址。因此,即使您的网站位于 example.com 域中,http://example.com/stuff也会被视为外部。

答案 1 :(得分:8)

您可以使用CSS attribute selectors根据href的值有条件地应用样式:



/* Links that start with "http" */
a[href^=http] { background-color:red; }

/* Links that don't start with "http" */
a:not([href^=http]) { background-color:lightgreen; }

/* Links that contain a specific domain name */
a[href*=example\.com] { background-color:lightblue; }

<a href="http://google.com/">external</a>
<a href="example.html">internal</a>
<a href="http://example.com">example.com</a>
&#13;
&#13;
&#13;

编辑:

正如JCOC611的回答中提到的那样,可以更灵活地省略&#34; http&#34;部分因为其他方案(ftp,git等)不匹配。

下面,我正在测试是否存在//而不是http。这将匹配其他方案以及网络路径引用。 (当然,它也会错误地将本地链接与不正确的双斜线匹配。)

&#13;
&#13;
/* Links that contain "//" */
a[href*='//'] { background-color:red; }
&#13;
<a href="//example.com">//example.com</a>
<a href="ftp://example.com">ftp://example.com</a>
<a href="example//fun.html">example//fun.html OOPS!</a>
<a href="example/fun.html">example//fun.html YAY!</a>
&#13;
&#13;
&#13;

答案 2 :(得分:5)

尚未,不;但是,在CSS Selectors Level 4下,有(可能是传入的):local-link伪类,例如:

a:local-link {
    color: red;
}

例如,假设这是在http://example.com上托管的页面上:

<a href="/another/page">Another page</a>
<a href="http://example.com/yet/another/page">Yet another page</a>
<a href="http://www.google.com/">Google</a>

上面的CSS会(或者至少应该,从我的阅读中)将所有链接设置为除红色之外的所有链接。

虽然这还没有在我尝试的任何浏览器中实现,但是。

话虽如此,对于具有绝对URL的<a>元素,attribute-starts-with选择器可以提供帮助(尽管它适用于href属性,而不是JavaScript href属性);所以

a[href^=http://example.com] {
    color: green;
}

仅适用于带有“又一页”字样的元素;因为前一个元素有一个根相对URL,尽管它是“本地”,但具有href属性,以'http://example.com'开头。

参考文献:

答案 3 :(得分:1)

对您的内部链接使用a[href='??']规则,并在没有外部链接的情况下使用其中一个:

a {
    background: green;
    color: white;
}
a[href*='http://www.my-website.com'] {
    background: blue;
    color: white;
}

确保按顺序放置它。使用添加了[href*=""]的{​​{1}}将确保获取包含给定字符串的任何href。

请在此处查看:http://jsfiddle.net/ur3rcymc/1/