2016-10-23 49 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>