PCとiPhoneでHTMLを共有するサイトを作る //CSS & Javascript

PC用とiPhone(iPod Touch)用にサイトを作る際に、レイアウトや、ボタンなどの細かなデザイン処理を替える必要はあるけれど、HTMLは更新性も考えて1つにしたいというジレンマに陥りました。

そこで、HTMLは1枚しか作成しませんが、読込ませるCSSを分岐させることでこれを実現するサンプルです。
下部のAタグでは、リンク先をそれぞれ別に指定するため、HTML内には2つの<a>が並んでいますが、クラス名に.pcbtnと.ipbtnを指定しておき、それぞれのCSSで、不要な方をdisplay:none;で指定して片方のみを表示するようにしてあります。
これは、<a>以外でも同様のクラスを使うことで、<div class="ipbtn">なら、div内をPCなら非表示にしたりすることも可能です。

サンプルページでは、PCとiPhoneで見た時で、コンテンツの幅と背景色、ボタンの飛び先が異なります。

サンプルページは以下から
iPhone&PCで、表示振り分けCSS サンプル
https://www.bute-studio.com/lab/iphone-btn/



サンプルHTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>iPhoneCSS_test</title>
<meta name="viewport" content="width=380" />
<link media="only screen and (max-device-width:480px)" href="iPhone.css" type="text/css" rel="stylesheet"/>
<link media="screen and (min-device-width:481px)" href="pc.css" type="text/css" rel="stylesheet"/>
<!--[if !IE]>-->
<link media="only screen and (max-device-width: 480px)" href="pc.css" type="text/css" rel="stylesheet" />
<!--<![endif]-->
</head>

<body>
<div id="wrapper">
<h1>iPhone&amp;PCで、表示振り分けCSS</h1>

<div id="pc">PC</div>
<div id="iphone">iPhone</div>

<a href="http://yahoo.co.jp" class="pcbtn">リンク(PC用)</a>
<a href="http://google.co.jp" class="ipbtn">リンク(iPhone用)</a>
</div>
</body>
</html>



サンプルiPhone.css
@charset "UTF-8";

#wrapper{
    width:320px;
    margin:0 auto;
}

#iphone{
    background:#3CF;
    color:#fff;
    width:100%;
    height:100px;

}

#pc{
    display:none;
}

.pcbtn{
    display:none;
}



サンプルPC.css
@charset "UTF-8";

#wrapper{
    width:900px;
    margin:0 auto;
}

#pc{
    background:#FCF;
    color:#fff;
    width:100%;
    height:100px;
}

#iphone{
    display:none;
}

.ipbtn{
    display:none;
}
Bookmark and Share


ブックマークに追加