SyntaxStudy
Sign Up
CSS Beginner 5 min read

Basic CSS Selectors

Basic CSS Selectors

CSS selectors are patterns used to select and style HTML elements. The three fundamental selectors are the element selector, the class selector, and the ID selector.

Element Selector

Targets every instance of an HTML tag on the page. For example, p { color: navy; } styles all paragraph elements.

Class Selector

Prefixed with a dot (.), a class selector targets any element that carries that class attribute. Classes are reusable — multiple elements can share the same class.

ID Selector

Prefixed with a hash (#), an ID selector targets the single element with that unique identifier. IDs must be unique within a document.

Specificity

When multiple rules compete, specificity decides which wins: ID (1-0-0) beats class (0-1-0) beats element (0-0-1).

Example
/* Element selector — targets every <p> tag */
p {
    color: navy;
    line-height: 1.6;
}

/* Class selector — reusable across many elements */
.highlight {
    background-color: #fff176;
    padding: 2px 4px;
    border-radius: 3px;
}

/* ID selector — unique element on the page */
#site-header {
    font-size: 2rem;
    font-weight: 700;
    border-bottom: 3px solid #1a73e8;
}

/* Combining selectors */
p.highlight {
    color: #b71c1c; /* only <p> tags with class highlight */
}
Pro Tip

Prefer classes over IDs for styling — IDs carry very high specificity that is hard to override, and they must be unique, limiting reuse.