CSS Selectors

CSS (Cascading Style Sheets) selectors are patterns used to select and style HTML elements. They allow you to target specific elements or groups of elements on a webpage. Here are some common CSS selectors:

Universal Selector (*):

  • Selects all elements on the page.

* {
    /* styles applied to all elements */
}

Type Selector:

  • Selects all instances of a given HTML tag.

p {
    /* styles applied to all <p> elements */
}

Class Selector (.classname):

  • Selects all elements with a specific class.

.highlight {
    /* styles applied to all elements with class="highlight" */
}

ID Selector (#id):

  • Selects a specific element with a given ID.

#header {
    /* styles applied to the element with id="header" */
}

Attribute Selector ([attribute], [attribute=value], [attribute~=value]):

  • Selects elements based on their attributes.

input[type="text"] {
    /* styles applied to text input elements */
}

a[href^="https"] {
    /* styles applied to links with href starting with "https" */
}

Descendant Selector (ancestor descendant):

  • Selects all descendants of a given ancestor element.

article p {
    /* styles applied to all <p> elements inside <article> */
}

Child Selector (parent > child):

  • Selects all direct children of a parent element.

ul > li {
    /* styles applied to all <li> elements that are direct children of <ul> */
}

Adjacent Sibling Selector (element + element):

  • Selects an element that is immediately preceded by a specified element.

h2 + p {
    /* styles applied to <p> elements that directly follow <h2> elements */
}

Pseudo-classes (:pseudo-class):

  • Selects elements based on their state or position.

a:hover {
    /* styles applied when the mouse hovers over a link */
}

input:checked {
    /* styles applied to checked radio buttons or checkboxes */
}

Pseudo-elements (::pseudo-element):

  • Selects a specific part of an element.

p::first-line {
    /* styles applied to the first line of each <p> element */
}

These are just some of the basic CSS selectors. Combinations of these selectors can be used to create more complex and specific styles for different elements on a webpage.

Leave a Reply

Your email address will not be published. Required fields are marked *