2016-10-23 47 views
-2

在我的网站中,我需要两种类型的<a>标签 - 一个用于内联链接,另一个用于独立链接。所以你可以想象我想要这两种类型的<a>标签有不同的颜色/款式。在CSS中定义一个自定义的<a>标签?

例如,对于内联链接,我不想让它们弹出太多,所以我想让它们下面的光线下划线。相反,我想要独立链接弹出,所以我想用鲜亮的蓝色将它们着色。

我的想法是创建两个标签,<a_inline><a>。我该怎么做?我尝试复制<a>,将副本重命名为<a_inline>,并修改了颜色属性等,但该东西不可点击。

+8

为什么不使用[类](https://jsfiddle.net/k3zp0x3v/)? –

+1

是使用类..这是典型情况.. – scaisEdge

回答

3

不要创建自己的元素,如果你这样做,那么你不再使用HTML。 (Custom elements是一件事,但在这里不合适)。

一般来说,这两个工具进行分组元素结合在一起是:

使用类组合看起来是这样的:

a { 
 
    color: red; 
 
} 
 
a.inline { 
 
    color: yellow 
 
}
<ul> 
 
    <li><a href="http://example.com">External link</a> 
 
    </li> 
 
    <li><a href="#foo" class="inline">Inline link</a> 
 
    </li> 
 
</ul>

而其他的做法是:

a { 
 
    color: red; 
 
} 
 
article a { 
 
    color: yellow 
 
}
<a href="http://example.com">External link</a> 
 

 
<article> 
 
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. <a href="#foo">Inline link</a>. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce 
 
    nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero.</p> 
 

 

 
</article>

在这种特殊情况下,然而,你已经在HTML足够的显着特征,以不需要添加任何东西。

假设我正确地理解你,你的内联链接将具有href属性,其值从#开始。您可以使用在attribute selector

a { 
 
    color: red; 
 
} 
 
a[href^="#"] { 
 
    color: yellow 
 
}
<ul> 
 
    <li><a href="http://example.com">External link</a> 
 
    </li> 
 
    <li><a href="#foo">Inline link</a> 
 
    </li> 
 
</ul>

+0

谢谢!对于第一种方法,我如何在新的'a.inline'中添加':hover'设置?现在,它似乎继承了'a:hover'的所有内容。 –

+0

实际上,我甚至不需要在新的'a.inline'中添加':hover'设置。只是想让'a.inline'没有':hover'效果。 –

+1

@SibbsGambling - 你把':hover'是你想要修改的选择器的其余部分 – Quentin

2

您正在寻找CSS classes 定义两类这样

a.one { 
    // Custom style one 
    color: blue; 
    text-decoration: underline; 
} 
a.two { 
    // Custom style two 
    color: cyan; 
    display: block; 
    text-decoration: none; 
} 

然后在你的HTML代码,只要你愿意,你可以同时使用。

<a class="one">One</a> 
<a class="two">Two</a> 
+0

有没有这样的事情作为一个CSS类。 HTML有类。 CSS有类选择器。 – Quentin

0

为了营造<a-inline>(注意-)你需要JavaScript和document.registerElement

否则,你可以做使用几件事情类属性选择器像:

/* all anchors */ 
 
a{ 
 
    color:red; 
 
} 
 
/* .gold anchors */ 
 
a.gold{ 
 
    color:gold; 
 
    text-decoration: underline; 
 
} 
 
/* ID fragment anchors */ 
 
a[href^='#']{ 
 
    color: blue; 
 
} 
 
/* Anchor href ends in .html */ 
 
a[href$='.html']{ 
 
    color: green; 
 
} 
 
/* Anchor is a http:// or https:// */ 
 
a[href^='http://'], 
 
a[href^='https://']{ 
 
    color: fuchsia; 
 
}
<a>I don't have any href</a><br> 
 
<a class="gold">I have a .gold</a><br> 
 
<a href="#something">I'm an ID anchor</a><br> 
 
<a href="./somepage.html">This is a .html link</a><br> 
 
<a href="http://stackoverflow.com">This is a http link</a><br>