What are selectors in HTML/CSS?
What are the class, id and element selectors?
Class selectors
- Used to apply CSS styling to multiple elements, for example
- In HTML <p class=”pStyle”>
- Can be referenced in CSS by accessing .pStyle { }
Id selectors
- Used to apply CSS styling to one element, for example
- In HTML <header id=”headerStyle”>
- Can be referenced in CSS by accessing #headerStyle { }
Element selector
- Used to apply CSS styling to all elements of a specific type, for example
- In CSS p{background-color: yellow;}
What is the nth-of-type, nth-child, first-child and last-child selectors?
Used when you want to style multiple elements or the first or last of an element
Reduces the amount of code needed to be written as you don’t need to add additional classes or ids
nth-of-type
- Selects a certain number of elements for a type of tag, for example
- p:nth-of-type(2) will select the 2nd <p> tag
- p:nth-of-type(odd) will select the <p> tags that are odd
- p:nth-of-type(3n + 1) – uses a formula and will select the 1st, 4th, 7th, 10th etc. <p>
nth-child
- Selects a child for that element based on the number entered, for example
- :nth-of-child(3) selects the third child element
first-child or last-child
- Selects the first or last child element for a tag