CSSをHTMLに適用させる方法
<link rel="stylesheet" href="style.css">
h1 {color: blue; background: yellow;}
#idname {color: red;}
p[class] {color: blue;}
a[href="xxx.com"][title] {font-size: 30px;}
* {color: blue}
h1, h2, h3 { color: blue;}
p > em {color: blue;}
a:hover {font-size: 30px;}
h1::first-letter
- 原則として同じ id は HTML 文書で 1 度しか使わないように推奨.
- idセレクタは他のidセレクタと結合はできない.
擬似クラスで動きを出す代表例
:hover
: カーソルが上にきた場合.
:active
: クリックされた場合.
:link
: リンクを訪問していない場合.
:visited
: リンクを訪問している場合.
擬似クラスでの特定位置の選択
:first-child
, `:last-child
: 兄弟要素の一番最初の要素、最後の要素を選択.
only-child
: 兄弟要素が存在しない要素を選択可能.
nth-child()
: 兄弟関係にある複数の要素を同時に指定する.
li:nth-child(2n+1) {color: red;}
li:nth-child(2) {color:red;}
擬似要素
h1::first-letter {font-size: 30px;}
h1::first-line {font-size: 30px;}
h2::before {
content: "Title : ";
color: gray;
}
a[href]::after {
content: url(https://xxx.png);
}
セレクタの選択尺度(詳細度)
h1 {color: red;} // 1
div h1 {color: red;} // 1 + 1 = 2
.special {color: red;} // 10
h2.special {color: red;} // 10 + 1 = 11
div#special {color: red;} // 100 + 1 = 101
!importnt
: 詳細度を無視してレイアウトを適当させる.
- 複数セレクタに適用されている場合は、通常と同じように詳細度の計算がされる.
- 実際に使用するとバグの元、あるいはデバッグが困難なため、基本的には使用しない.
p {
color: blue!important;
}
- 詳細度が完全に同じ場合、CSSの最後にあるルールを優先する.
継承
- たとえば
<ul>
タグにスタイルを適用すれば、子要素の<li>
にもスタイルが継承される.
- 継承を避けたい場合、
initial
を使用する.
<h1>I am <strong>a</strong> pen.</h1>
h1 {
color: red;
}
strong {
color: initial;
}