CSS を組版に使うときに注意すべきこと(入門編その2)

こんにちは、『AH Formatter』のサポート担当です。
前回、CSS でレイアウトを実現する上で注意すべき点を挙げてみました。[1]
おさらいすると、
・セレクタで対象を決めて、プロパティと値でスタイル付けすること
・セレクタは多重定義できること
・優先順位があること
などです。
優先順位は大雑把に言ってしまえば、
1.Style=””
2.idセレクタ
3.classセレクタ、属性セレクタなど
の順番に低くなります。

詳しい仕様は、
http://www.w3.org/TR/css3-selectors/
に載っています。
日本語の解説サイトもたくさんあります。
私もまだまだ勉強中です。

実際のところ、一番頻繁に使われているのは <div class=”~”> のタイプかと思います。
コンテンツを divタグで囲って classセレクタでレイアウトを指定します。

.hoge{
border-style:solid;
border-color:#fbbdaf;
border-width:10px 10px 10px 10px;
color:#000000;
font-size:90%;
padding:0.1em 0.4em;
}

<div class=”hoge”>
<p>Antenna House</p>
<p>AH Formatter</p>
</div>

出力結果

ネストしたdiv構造で次のようなケースはよくあります。

.default{
background-color: #900;
padding:10pt;
font-size:20pt;
}
.test{
color:red;
border-top-style:dotted;
border-top-width:10pt;
border-top-color:yellow;
}
.test2{
border-style:solid;
border-width:5pt;
}
.test3{
border-bottom-color:blue;
}

<div class=”default”>
<div class=”test test2 test3″>
<p>Antenna House</p>
</div>
</div>

この場合、競合したスタイルは、後から指定されたものが優先になります。
組版結果は次の通り。

出力結果

さらに、前回、同じセレクタに対して何度でも指定することができると書きました。
上記の例で、
.default{
background-color: #00EE40;
}
を追加したらどうなるでしょう。
この場合も後から定義されたものが有効になります。

次に、CSS が外部ファイルに定義されていて、
このふたつの defaultクラスが別々のファイル(”styleA.css” と “styleB.css”)に保存されていたら?

<link rel=”stylesheet” type=”text/css” href=”styleA.css” />
<link rel=”stylesheet” type=”text/css” href=”styleB.css” />

答えは、”styleB.css” の.default{ }が有効になります。
この順番が変わるだけで結果が違ってきてしまいますね。ああ恐ろしい。

実際にサポート業務をしていると、次のようなデータを見ることが多くあります。

<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”content-type” content=”text/html; charset=utf-8″/>
<title>Test</title>
<link rel=”stylesheet” type=”text/css” href=”style-A.css” />
<link rel=”stylesheet” type=”text/css” href=”style-B.css” />
.
.
.
<link rel=”stylesheet” type=”text/css” href=”style-X.css” />
<link rel=”stylesheet” type=”text/css” href=”style-Y.css” />
<link rel=”stylesheet” type=”text/css” href=”style-Z.css” />

</head>
<body>
<h1>Test</h1>
<div class=”A B C D”>
<div class=”E F G”>
<div class=”H I J K L M N” id=”sample”>
<div class=”O”>
<p>………</p>
<ol class=”M A Z”>
<li>……</li>
<li>……</li>
<li>……</li>
</ol>
</div>
</div>
</div>
</div>
</body>
</html>

こんな状態でレイアウトを変更しようとなった時に、
どこを変更したらいいかをすぐに判断するのは難しいですね。
CSS はレイアウトを分離して共通化して運用できるのでとても便利ですが、
複数の開発者が共有するような場合には工夫しないと破綻してしまいそうです。
設計段階での明示的なルール決めと共に、
シンプルなオーサリングやレイアウト設定が必要になります。

続きのお話はまたいずれ。

[1] CSS を組版に使うときに注意すべきこと(入門編)