CSS Core Selectors
CSS core selectors form the basis for targeting HTML elements, enabling control over their appearance and behavior.
Introduction
CSS core selectors are the foundation of selecting elements in your HTML structure. They allow you to target specific elements and apply styles to them. These selectors are essential for controlling the appearance and behavior of your web pages.
ID Selector
The ID selector targets a specific element using its unique ID attribute. It is denoted by a hash symbol (#) followed by the ID name.
Example:
#my-id {
color: blue;
font-size: 16px;
}
This is a paragraph with a unique ID. This style will apply only to the paragraph with the ID my-id
.
Class Selector
The class selector targets elements with a specific class attribute. It is denoted by a dot (.) followed by the class name.
Example:
.my-class {
background-color: lightgray;
padding: 10px;
}
This is a paragraph with the my-class class. This style will apply to any element that has the class my-class
.
Element Selector
The element selector targets all elements of a specific type. It uses the element's tag name.
Example:
p {
font-family: Arial, sans-serif;
line-height: 1.5;
}
This is a paragraph. This style will apply to all paragraph elements (<p>
) on the page.
Do You Know?
You can combine multiple selectors to create more specific rules. For example, p.my-class
would target paragraphs with the class my-class
.
Avoid This
Avoid using IDs for styling unless you absolutely need to target a single element. Classes are more flexible and reusable.
Summary
- ID selectors target elements by their unique ID.
- Class selectors target elements by their class name.
- Element selectors target all elements of a specific type.
- Combining selectors allows for more precise targeting.