LoginSignup
7
9

More than 5 years have passed since last update.

URLのパラメータによって要素のスタイルを変更する方法

Posted at

jsでやるほどでもないし、cssで出来ないかな〜と調べていたらtargetという擬似クラスが存在するらしい。
よくページ内リンクで使われるあれ「 URL#section1 」 みたいなやつです。
ただしくはパラメータではなく、フラグメント識別子という名称で特定の要素に対して操作を行いたい場合に使用するとのこと
http://d.hatena.ne.jp/keyword/%A5%D5%A5%E9%A5%B0%A5%E1%A5%F3%A5%C8%BC%B1%CA%CC%BB%D2

このtarget擬似クラスを使用してスタイルを書いてみる

sample.html
<html>
<head></head>
<body>
  <div class="box" id="box1"></div>
  <div class="box" id="box2"></div>
</body>
</html>
sample.css
.box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
/* box1のid */
.box:target{
  background-color: red;
}
/* notは引数に指定されたid or class以外 */
.box:not(:target){
  background-color: blue;
}

sample.html#box1 にアクセスした場合
スクリーンショット 2016-01-05 4.34.47.png

sample.html#box2 にアクセスした場合

スクリーンショット 2016-01-05 4.35.01.png

7
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9