SmartCodingTips

Basic CSS Selectors

CSS selectors are patterns used to target and apply styles to HTML elements. Basic selectors let you select elements by tag, class, ID, or universally.

1. Universal Selector (*)

Applies styles to all elements on the page.


* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
            

2. Element Selector

Targets all elements of a specific type (e.g., all <p> or <h1> tags).


p {
    font-size: 18px;
    color: #333;
}
            

3. Class Selector (.)

Targets elements with a specific class attribute. Classes can be reused on multiple elements.


.highlight {
    background-color: yellow;
    font-weight: bold;
}
            

HTML usage: <p class="highlight">Important Text</p>

4. ID Selector (#)

Targets a single element with a specific id. IDs should be unique on each page.


#header {
    background-color: #1e3a8a;
    color: white;
    padding: 10px;
}
            

HTML usage: <div id="header">Site Header</div>

5. Grouping Selector

Apply the same styles to multiple elements by separating selectors with commas.


h1, h2, h3 {
 font-family: 'Segoe UI', sans-serif;
 color: #1f2937;
}
            

Conclusion

Mastering basic selectors is essential for applying styles effectively. Once you're comfortable with these, you can move on to more advanced combinators and pseudo-selectors.