The Front-End
CSS
CSS Selectors

CSS Selectors

CSS (Cascading Style Sheets) selectors are patterns that define which elements in an HTML document should be styled by a set of CSS rules. Selectors allow you to target specific elements or groups of elements based on their HTML structure, attributes, and relationships. Here's a brief introduction to CSS selectors:

  1. Basic Element Selectors
  2. Class Selectors
  3. ID Selectors
  4. Attribute Selectors
  5. Descendant Selectors
  6. Child Selectors
  7. Adjacent Sibling Selectors
  8. Pseudo-classes
  9. Pseudo-elements
  10. Grouping Selectors
  11. Universal Selector
  12. :not() Pseudo-class

Basic Element Selectors

The most straightforward selector targets HTML elements directly. For example, to style all paragraphs:

/* Selects all paragraphs */
p {
  color: blue;
  font-size: 16px;
}

Class Selectors

Use class selectors to style elements with a specific class attribute:

/* Selects elements with the class 'highlight' */
.highlight {
  background-color: yellow;
  font-weight: bold;
}

Apply the class to HTML elements:

<p class="highlight">This paragraph is highlighted.</p>

ID Selectors

ID selectors target a single unique element:

/* Selects the element with the ID 'main-heading' */
#main-heading {
  font-size: 24px;
  color: green;
}

Apply the ID to an HTML element:

<h1 id="main-heading">Main Heading</h1>

Attribute Selectors

Use attribute selectors to style elements based on their attributes:

/* Selects all links with the 'target' attribute */
a[target="_blank"] {
  color: red;
}

Descendant Selectors

Descendant selectors target nested elements:

/* Selects all paragraphs inside a div */
div p {
  margin: 10px;
}

Child Selectors

Child selectors specifically target direct children:

/* Selects only immediate list items of an unordered list */
ul > li {
  list-style-type: square;
}

Adjacent Sibling Selectors

Adjacent sibling selectors target elements that share the same parent:

/* Selects the paragraph immediately following a heading */
h2 + p {
  font-style: italic;
}

Pseudo-classes

Pseudo-classes style elements based on their state or position:

/* Selects the first child of an element */
li:first-child {
  font-weight: bold;
}

Pseudo-elements

Pseudo-elements style parts of an element, like the first line or first letter:

/* Selects the first line of a paragraph */
p::first-line {
  text-transform: uppercase;
}

Grouping Selectors

Group selectors to apply the same styles to multiple elements:

/* Styles both paragraphs and list items */
p, li {
  color: purple;
}

Universal Selector

The universal selector selects all elements:

/* Selects all elements and sets margin to 0 */
* {
  margin: 0;
}

:not() Pseudo-class

Use the :not() pseudo-class to exclude certain elements:

/* Selects all list items except the first one */
li:not(:first-child) {
  color: gray;
}