CSSの指定
今回はCSSを指定する方法をやります。CSSの指定
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSSのテストページ</title>
<style type="text/css">
/* タグ指定 */
body {
/* 背景色 */
background-color: green;
}
p {
/* 文字色 */
color: red;
}
/* クラス指定 */
.class {
/* 文字色 */
color: white;
}
/* タグの中のクラス指定 */
div .class {
/* 背景色 */
background-color: blue;
}
/* Id指定 */
#id {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p class="class" >CLASS1</p>
</div>
<p class="class" >CLASS2</p>
<p id="id">ID</p>
</body>
</html>
実行イメージ

優先順
優先順は、style直接指定→id指定→class指定→タグ指定の順。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSSのテストページ</title>
<style type="text/css">
* {
/* 背景色 */
background-color: gray;
}
body {
/* 背景色 */
background-color: green;
}
div {
/* 背景色 */
background-color: blue;
}
p {
/* 背景色 */
background-color: white;
}
.class {
/* 背景色 */
background-color: red;
}
#id1,#id2 {
/* 背景色 */
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p id="id1" class="class" style="background-color: pink;">styleを直接指定が優先順1番</p>
<p id="id2" class="class">id指定が優先順2番</p>
<p class="class">class指定が優先順3番</p>
<p>タグ指定が優先順4番</p>
</div>
body指定
</body>
</html>
実行イメージ

!importantを付けると、それが最優先になる。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSSのテストページ</title>
<style type="text/css">
* {
/* 背景色 */
background-color: gray;
}
body {
/* 背景色 */
background-color: green;
}
div {
/* 背景色 */
background-color: blue;
}
p {
/* 背景色 */
background-color: white !important;
}
.class {
/* 背景色 */
background-color: red;
}
#id1,#id2 {
/* 背景色 */
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p id="id1" class="class" style="background-color: pink;">styleを直接指定が優先順1番</p>
<p id="id2" class="class">id指定が優先順2番</p>
<p class="class">class指定が優先順3番</p>
<p>タグ指定が優先順4番</p>
</div>
body指定
</body>
</html>
実行イメージ

区切り文字
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSSのテストページ</title>
<style type="text/css">
/* スペース区切りは 親 子or孫 の関係 */
.cls p{
/* 文字色 */
color: red;
}
/* 大なりカッコ区切りは 親>子 の関係 */
.cls > p{
/* 背景色 */
background-color: yellow
}
/* プラス区切りは 直後の要素 */
#id2 + p{
/* フォントサイズ */
font-size: xx-large;
}
/* チルダ区切りは 以降の要素 */
#id2 ~ p{
/* 取り消し線 */
text-decoration: line-through;
}
/* カンマ区切りは 複数指定(or) */
#id1 , #id5{
/* 罫線 */
border: solid 1px blue;
}
</style>
</head>
<body>
<div class="cls">
<div>
<p id="id1">id1(孫、複数指定)</p>
</div>
<p id="id2">id2(子)</p>
<p id="id3">id3(子、直後)</p>
<p id="id4">id4(子、以降)</p>
</div>
<p id="id5">id5(複数指定)</p>
</body>
</html>
実行イメージ

子指定
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CSSのテストページ</title>
<style type="text/css">
/* 最初の子 */
.cls p:first-child{
/* 文字色 */
color: yellow;
}
/* 最後の子 */
.cls p:last-child{
/* 文字色 */
color: blue;
}
/* 2番目の子 */
.cls p:nth-child(2){
/* 文字色 */
color: red;
}
/* 奇数の子 */
.cls p:nth-child(2n+1){
/* 背景色 */
background-color: green;
}
</style>
</head>
<body>
<div class="cls">
<p>最初の子</p>
<p>2番目の子</p>
<p>子</p>
<p>最後の子</p>
</div>
</body>
</html>
実行イメージ

ページのトップへ戻る