Syntax
selector {
property1: value1;
property2: value2;
}
The new lines are ignored so it’s equivalent to the following:
selector {
property1: value1; property2: value2;
}
selector { property1: value1; property2: value2; }
When it’s just a single definition I like to write it in a single line:
selector { property: value; }
Example
h1 {
color: blue;
}
Most Common Selectors
- Element
- Class
- ID
ID
The id
attribute should be unique among the rest of the element in the same
webpage.
<h1 id="shimon">
whatever
</h1>
Using ID Selector
Syntax:
#id-name {
property: value;
}
Example:
#shimon {
color: green;
}
Class
<h1 class="bamba">
whatever
</h1>
Using Class Selector
Syntax:
.class-name {
property: value;
}
Example:
.shimon {
color: green;
}
Grouping Selector
Without group selector:
h1 {
color: blue;
}
h2 {
color: blue;
}
With group selector:
h1, h2 {
color: blue;
}
Multiple Class
<h1 class="shimon nissim doron">
pompa
</h1>
Pay attention to the space delimiter!
Using Class Selector
Syntax:
.class-name {
property: value;
}
Example:
.bamba {
color: yellow;
}
Selectors can combine!
Examples
No space between the two selectors:
.class-1.class-2 {
property: value;
}
div.class-1 {
property: value;
}
div.class-1.class-2 {
property: value;
}
#shimon.class-1 {
property: value;
}
#shimon.class-1.class-2 {
property: value;
}
div#shimon.class-1.class-2 {
property: value;
}
Descendants Combinator
Pay attention to the space!
.ancestor .descendant {
properties: value;
}
Child Combinator
.parent > .child {
properties: value;
}
Descendant $\neq$ Child
Combine The Previous Ones
header.shimon h1.david {
color: blue;
}
Universal Selector
* {
font-family: Ariel;
}
So far we should understand the meaning of the following selectors:
div {}
#nisim {}
.shlomo {}
.class1.class2 {}
nav li {}
nav > li {}
* {}
Psaudo Class
A selector that is used to define a special state of an element.
Syntax:
selector:pseudo-class {
property: value;
}
Hover
li:hover {
background-color: red;
}
Hover combined with a class selector:
li.nisim:hover {
background-color: red;
}
More combinations:
p {
display: none;
}
div:hover p {
display: block;
}
:first-child
p:first-child {
background-color: red;
}
:focus
input:focus {
background-color: red;
}
:nth-child(pattern)
li:nth-child(3) { background-color: red; }
li:nth-child(odd) { background-color: red; }
li:nth-child(even) { background-color: red; }
li:nth-child(3n) { background-color: red; }
li:nth-child(3n + 1) { background-color: red; }
Anchor States
a:link { color: red; }
a:visited { color: blue; }
a:hover { color: green; }
a:active { color: yellow; }
Inputs States
input:checked { background-color: green; }
input:disabled { background-color: red; }
input:valid { background-color: green; }
input:invalid { background-color: red; }
input:required { background-color: red; }
input:optional { background-color: green; }