Web4College

CSS element selectors

1. Type selectors (tag name)

The type selectors select the elements based on the structure i.e. whether it is child element or immediately next element. There are also different combinators (whitespace, greater-than sign (>), aterisk('*'), plus-sign ('+')) that are used to select and design the specific elements.

Example
Try it
<style>
p{
  font-size:20px;
  color:red;
}
</style>

p is a selector that specifies font-size and color of the text for the <p> element.

2. Selectors list

It represents a list of the individual selectors separated by comma. In this case, same CSS properties can be specified for all of the selectors.

Example
Try it
<style>
p{
  font-family:papyrus;
  background-color:red;
}
code{
  font-family:papyrus;
  background-color:red;
}
kbd{
  font-family:papyrus;
  background-color:red;
}
</style>

It is the same as

Example
Try it
<style>
p, code, kbd{
  font-family:papyrus;
  background-color:red;
}
</style>

3. Universal selector

The universal selector selects all of the elements in a page. Asterisk ('*') represents a universal selector.

Example
Try it
<style>
*{
  font-size:20px;
  color:red;
}
</style>

4. Combinator

Combinators represent different relationships between two individual elements. There are different kind of combinators. It includes descendent (whitespace), child (<gt>), next-sibling (+), following (~) and reference (/attribute/) combinators.

4.1 Descendent combinator

Descendent combinator is represented by whitespace between to selectors. In this case, the second selector is an orbitrary descendent of the first one.

Example
Try it
<style>
div p{
  font-weight:900px;
  background-color:green;
}
</style>

It designs the <p> element that is an orbitrary descendent of the <div> element.

4.2 Child combinator

Child combinator represents child-parent relationship. It is represented by the greater-than sign (>) that separates two selectors. It designs the child element of the parent element.

Example
Try it
<style>
ol > li{
  padding:5px;
  background-color:lightblue;
}
</style>

In this example, <li> is the child element of the <ul>.

4.3 Next-sibling combinator

Plus-sign represents the next-sibling combinator between two individual selectors. The second selector is present immediately next to the first selector.

Example
Try it
<style>
p+code{
  font-family:fantasy;
  color:red;
}
</style>

It defines CSS properties for the <code> element that is next (immediately) to the <p> element.

4.4 following combinator

It resembles nex-sibling combinator partially. It is represented by the tilde (~) that separates two selectors. The second selector should follow the first one (not necessarily immediate).

Example
Try it
<style>
code ~ kbd{
  font-family:cursive;
  color:rgb(0,225,0);
}
</style>

In this case, kbd is not necessarily immediate next to the code.

See CSS selectors cheat sheet