CSS Selectors
CSS Selectors
elements on a webpage. It defines which HTML elements the styles will be applied to.
A CSS selector consists of a pattern used to select elements. The basic syntax includes:
selector {
property: value;
h1 {
color: blue;
font-size: 24px;
Types of selectors:
1. Universal Selector (*)
The universal selector targets all elements on the page. It’s used when you want to apply a
style universally to every element.
Example:
{
color: black;
font-family: Arial, sans-serif;
}
In this example, every element on the page will have black text color and the font will be
Arial (or the next available sans-serif font).
Example:
h1 {
font-size: 2em;
color: darkblue;
}
This rule targets all <h1> tags and applies a font-size of 2em and a color of dark blue. All
<h1> elements on the page will be affected.
Example:
.button {
background-color: blue;
color: white;
padding: 10px;
}
This will apply the defined styles (blue background, white text, and 10px padding) to any
element that has the class="button".
HTML:
<button class="button">Click Me</button>
<p class="button">This is a paragraph with a button class.</p>
Both the <button> and <p> elements will be styled with the .button class.
4. ID Selector (#)
The ID selector targets an element with a specific id attribute. IDs are unique, meaning they
should only be used once per page.
Example:
#header {
background-color: lightgray;
text-align: center;
}
This will style the element with id="header" (like <div id="header">) to have a light gray
background and center-aligned text.
HTML:
<div id="header">This is the header</div>
In this case, only the element with the id="header" will be affected.
5. Attribute Selector
The attribute selector allows you to target elements based on the presence or value of a
specific attribute.
Example 1
input[type="text"] {
border: 1px solid black;
}
This targets all <input> elements with a type="text" attribute and applies a black border
around them.
6.Pseudo-elements
o Pseudo-elements are used to target specific parts of an element, such as its
first letter, first line, or content before or after the element.
Examples:
1. ::before: Inserts content before the element's content.
2. ::after: Inserts content after the element's content.
3. ::first-letter: Targets the first letter of the element's content.
p::first-letter {
font-size: 2em;
color: red;
}
p::before {
content: "Note: ";
font-weight: bold;
}
p::after {
content: " (end)";
font-style: italic;
}
p::first-letter: Targets the first letter of all <p> elements and makes it larger and red.
p::before: Inserts the text "Note: " before the content of each <p>.
p::after: Inserts the text " (end)" after the content of each <p>.