data属性とCSSのcontentを使って、PCとスマホで画像とテキストを出し分ける方法をメモ。
サンプルコード
HTML
<nav class="gnav"> <ul class="gnav-inner"> <li class="gnav-item"> <a href="" data-menu="MENU A"> <img src="./menu01.png" width="180" height="40" alt="MENU A" /> </a> </li> <li class="gnav-item"> <a href="" data-menu="MENU B"> <img src="./menu02.png" width="180" height="40" alt="MENU B" /> </a> </li> <li class="gnav-item"> <a href="" data-menu="MENU C"> <img src="./menu03.png" width="180" height="40" alt="MENU C" /> </a> </li> <li class="gnav-item"> <a href="" data-menu="MENU D"> <img src="./menu04.png" width="180" height="40" alt="MENU D" /> </a> </li> <li class="gnav-item"> <a href="" data-menu="MENU E"> <img src="./menu05.png" width="180" height="40" alt="MENU E" /> </a> </li> </ul> </nav>
CSS
/* SP用 */
@media screen and (max-width: 768px) {
.gnav-item {
border-bottom: #999999 1px solid;
}
.gnav-item a {
display: block;
padding: 10px;
color: #000000;
text-decoration: none;
}
.gnav-item a:before {
content: attr(data-menu);
}
.gnav-item img {
display: none;
}
}
/* PC用 */
@media screen and (min-width: 769px) {
.gnav {
background: #ccc;
}
.gnav-inner {
width: 900px;
height: 40px;
margin: 0 auto;
}
.gnav-item {
float: left;
}
}
スマホ時はaタグのdata属性(data-menu)の内容をcontentで出して、imgは非表示にしています。
画像とテキストを出し分けるデモページ
【参考サイト】
コメントが承認されるまで時間がかかります。