Introduction to selectors
CSS (Cascading Style Sheets) selectors are patterns used to select the HTML elements you want to style. They are fundamental to applying styles effectively and efficiently. Here's an introduction to CSS selectors with some interesting examples:
Basic Selectors
-
Universal Selector (
*)- Selects all elements.
* { margin: 0; padding: 0; } -
Type Selector
- Selects all elements of a given type.
p { color: blue; } -
Class Selector (
.)- Selects all elements with a specific class attribute.
.highlight { background-color: yellow; } -
ID Selector (
#)- Selects an element with a specific ID attribute.
#header { font-size: 24px; }
Attribute Selectors
-
Attribute Selector (
[attribute])- Selects elements with a specific attribute.
[data-role="button"] { cursor: pointer; } -
Attribute Value Selector (
[attribute="value"])- Selects elements with a specific attribute value.
[type="text"] { border: 1px solid black; }
Pseudo-Classes
-
Pseudo-Classes (
:)- Selects elements based on their state.
a:hover { color: red; } -
First Child (
:first-child)- Selects the first child of a parent element.
p:first-child { font-weight: bold; } -
Nth Child (
:nth-child(n))- Selects the nth child of a parent element.
li:nth-child(odd) { background-color: lightgray; }
Combinators
-
Descendant Combinator (
)- Selects all elements that are descendants of a specified element.
div p { color: green; } -
Child Combinator (
>)- Selects all direct children of a specified element.
ul > li { list-style-type: none; } -
Adjacent Sibling Combinator (
+)- Selects the element that is immediately adjacent to a specified element.
h1 + p { margin-top: 0; } -
General Sibling Combinator (
~)- Selects all siblings of a specified element.
h1 ~ p { color: blue; }
Pseudo-Elements
-
Pseudo-Elements (
::)- Selects a specific part of an element.
p::first-line { font-weight: bold; } -
Before and After (
::beforeand::after)- Inserts content before or after an element's content.
p::before { content: "Note: "; font-weight: bold; }
Interesting Examples
-
Styling Odd and Even Rows in a Table
tr:nth-child(odd) { background-color: #f2f2f2; } tr:nth-child(even) { background-color: #ffffff; } -
Styling the First Letter of a Paragraph
p::first-letter { font-size: 200%; color: red; } -
Styling Form Inputs Differently Based on Type
input[type="text"] { border: 1px solid blue; } input[type="submit"] { background-color: green; color: white; } -
Styling Links Differently Based on Their State
a:link { color: blue; } a:visited { color: purple; } a:hover { color: red; } a:active { color: orange; }
CSS selectors are powerful tools that allow you to target specific elements and apply styles precisely. Understanding and using them effectively can greatly enhance the design and functionality of your web pages.
No comments to display
No comments to display