Selectors

Selectors

There are multiple types of selectors we can use to target elements in CSS
  1. Universal * All properties are inherited to every element, used for base resets
*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; } html { font-size: 62.5%; /* changes the rem = 10px for ease */ }
  1. Type Used to target by element name. The same selector
p { color: orange; }
  1. Class Used to group similar types together
.bold { font-weight: bold; }
  1. ID Used to target unique elements
#header { margin-bottom: 1rem; }
  1. Attribute Let’s say there are many input elements and we want to target the ones with password field
input[type=”password”] { border: 1px solid black; }
  1. Descendant All the child no matter how level deep. This will target all the p tags inside div any level nested
div p { color: red; }
  1. Direct Child Will target all the paragraphs within the div tag that are direct child
div > p { color: red; }
  1. Adjacent Sibling It means the very next element on same level. All the ul that are directly after the paragraph
p + ul{ color: red; }
  1. General Sibling Selects all the elements that are next siblings of a specified element. This will target all the p after h1
h1 ~ p { color: red; }
  1. Multiple Selector (Grouping) This targets multiple
ul, p, h1 {}

Pseudo Class (:)

  • Used to target different states like when mouse enters a certain element, etc.
  • :hover (on mouse hover), :focus (for input elements on tab keypress), :active (click), :nth-child(2n) for even items

Pseudo Elements (::)

  • before, after, first-line, first-letter, selection (When the text is selected)
  • ::after, ::before is used to add fake content using CSS for stylistic purposes. Only shows up after the actual content. Suppose we have a box div with some content and then after will show the content after the text not the box.
el::after { content: "Hey"; }