CSS Basic Selectors
In CSS, selectors are used to target specific HTML elements to which you want to apply styles. Here are some of the most basic and commonly used selectors:
1. Type Selector
- Syntax: element_name (e.g., p, h1, div, span)
- Purpose: Targets all elements of a specific HTML tag type.
- Example:
p { color: blue; font-size: 16px; }
This rule will style all <p> (paragraph) elements on the page with blue text and a font size of 16 pixels.
2. Type Selector
- Syntax: followed by the class name (e.g., .myClass)
- Purpose: Targets all elements that have the specified class attribute.
- Example:
//HTML
<div class="myClass">
This text has the "myClass" applied.
</div>
//CSS
.myClass {
background-color: lightgray;
padding: 10px;
}
This will style any element with the class “myClass” with a light gray background and 10px of padding.
3. ID Selector
- Syntax: # followed by the ID name (e.g., #myId)
- Purpose: Targets a single, unique element with the specified ID attribute. IDs should be unique within an HTML document.
- Example:
//HTML
<h1 id="mainHeading">
Welcome to the Page
</h1>
//CSS
#mainHeading {
color: red;
font-size: 24px;
}
This will style the <h1> element with the ID “mainHeading” with red text and a font size of 24 pixels.
4. Universal Selector
- Syntax: *
- Purpose: Targets all elements in the HTML document.
- Example:
* {
margin: 0;
padding: 0;
}
This rule will remove default margins and padding from all elements on the page.