CSSでPDFやExcelなどのリンクに自動でアイコンを付ける方法
- Category :
- CSS リファレンス

PDF、Excel、Word、ZIPや外部リンクなどにアイコンが付けるが付いてるサイトって見かけると思うですがこれを自動でつくようにCSSで指定する事が出来るので紹介しておきます。
Coding Architectureさんの「外部リンクだけにアイコンをつける」を参考にさせて貰いました。
…ここからが続き
外部リンク

<a href="http://www.google.co.jp/">外部リンク</a>
/* 外部リンク要素
----------------------------------------------------------- */
a[href^="http"] {
background: url(image/icon/external.gif) no-repeat 100% 50%;
}
* html a.external {
background: url(image/icon/external.gif) no-repeat 100% 50%;
}
a[href^="http://www.css-lecture.com/"] {
padding: inherit;
background: transparent;
}

<a href="test.pdf">pdf</a>
/* pdf要素
----------------------------------------------------------- */
a[href$=".pdf"] {
background: url(image/icon/pdf.gif) no-repeat 100% 50%;
}
* html a.pdf{
background: url(image/icon/pdf.gif) no-repeat 100% 50%;
}
Word

<a href="test.doc">doc</a>
/* Word要素
----------------------------------------------------------- */
a[href$=".doc"] {
background: url(image/icon/doc.gif) no-repeat 100% 50%;
}
* html a.doc {
background: url(image/icon/doc.gif) no-repeat 100% 50%;
}
Excel

<a href="test.xls">xls</a>
/* Excel要素
----------------------------------------------------------- */
a[href$=".xls"] {
background: url(image/icon/xls.gif) no-repeat 100% 50%;
}
* html a.xls{
background: url(image/icon/xls.gif) no-repeat 100% 50%;
}
ZIP

<a href="test.zip">zip</a>
/* zip要素
----------------------------------------------------------- */
a[href$=".zip"] {
background: url(image/icon/zip.gif) no-repeat 100% 50%;
}
* html a.zip{
background: url(image/icon/zip.gif) no-repeat 100% 50%;
}
mailto

<a href="mailto:miya@css-lecture.com">miya@css-lecture.com</a>
/* mailto要素
----------------------------------------------------------- */
a[href ^="mailto:"] {
background: url(image/icon/mailto.gif) no-repeat 100% 50%;
}
* html a.mailto {
background:url(image/icon/mailto.gif) no-repeat 100% 50%;
}
注意事項など
リンクタグの共通要素にアイコン部分のpaddingで余白を作っておく事。IE6にも対応させる為に下記ソースも入れて下さい。
a {
padding: 4px 20px 4px 0;
}
/* IE-6要素
----------------------------------------------------------- */
* html a{
behavior: expression(
this.className += this.getAttribute("href").match(/^http.*/) && (!this.getAttribute("href").match("css-lecture.com")) ? " external" : "",
this.className += this.getAttribute("href").match(/\.pdf$/) ? " pdf" : "",
this.className += this.getAttribute("href").match(/\.doc$/) ? " doc" : "",
this.className += this.getAttribute("href").match(/\.xls$/) ? " xls" : "",
this.className += this.getAttribute("href").match(/\.zip$/) ? " zip" : "",
this.className += this.getAttribute("href").match(/^mailto.*/) ? " mailto" : "",
this.style.behavior = "none"
);
}
アイコンへのパスやドメイン名などは自分のサイトに合わせて下さいね!




Comments
こんにちは
この方法でつけたアイコンにalt で説明をつけるにはどうしたらよいのでしょうか。
こちらの方法があることがわかりました。
http://www.koikikukan.com/archives/2006/09/13-010005.php
しかし、html側のタグにtitle属性をつけないと反映されないので、CSSだけで解決する方法がないようです。