CSS Selector-Child, Sibling, Attribute, :first-child, nth-child(2n)

In CSS (Cascading Style Sheets), selectors are used to target specific HTML elements for styling. Here are some advanced selectors along with examples:

Child Selector (>):

  • Selects direct children of a parent element.
Copy code
/* Selects all direct <p> children of the element with class "container" */
.container > p {
    color: blue;

Adjacent Sibling Selector (+):

  • Selects an element that is directly adjacent to another element.

/* Selects the <span> directly adjacent to an <h2> */
h2 + span {
    font-weight: bold;

Attribute Selector:

  • Selects elements based on their attributes.

/* Selects all elements with a "data-category" attribute */
[data-category] {
    background-color: yellow;

General Sibling Selector (~):

  • Selects all sibling elements that follow an element.

/* Selects all <p> elements that are siblings following an <h2> */
h2 ~ p {
    margin-top: 10px;


  • Selects the first child element of its parent.

/* Selects the first <li> in a list */
li:first-child {
    font-weight: bold;


  • Selects every even child element.

/* Selects every even <tr> in a table */
tr:nth-child(2n) {
    background-color: lightgray;

These selectors provide a powerful way to target and style specific elements in your HTML documents. Remember that browser compatibility may vary for some of these selectors, so it’s a good idea to check compatibility if you have to support older browsers.

Pseudo Class - hover, focus, active and Pseudo Element - before, after
Overflow - scroll, auto, visible, hidden, overflow-x, overflow-y