In CSS, selectors are used to target HTML elements that you want to style. Here is a brief overview of the main selector types and their purposes.
-
Element Selectors (Type Selectors):
- Select elements directly by their tag name.
- For example,
p { color: red; }sets the text color of all<p>elements to red.
-
Class Selectors:
- Select elements using the HTML element's class attribute.
- For example,
.menu { font-size: 16px; }applies to all elements with the classmenu.
-
ID Selectors:
- Select a specific element using its HTML ID.
- For example,
#header { background-color: blue; }sets the background color of the element with IDheaderto blue.
-
Attribute Selectors:
- Select elements based on their attributes and attribute values.
- For example,
input[type="text"] { border: 1px solid black; }selects all text input fields and sets their border.
-
Pseudo-class Selectors:
- Used to select elements in specific states, such as when hovered over by the mouse.
- For example,
a:hover { color: green; }changes the link color to green when the mouse hovers over it.
-
Pseudo-element Selectors:
- Used to select specific parts of an element, such as the first line or first letter.
- For example,
p::first-letter { font-size: 200%; }sets the font size of the first letter of each paragraph to twice the original size.
-
Descendant Selectors:
- Select descendant elements within an element.
- For example,
div p { color: blue; }sets the text color of all<p>elements inside a<div>to blue.
-
Child Selectors:
- Select only direct child elements.
- For example,
ul > li { list-style-type: none; }removes the list style from<li>elements directly under a<ul>.
-
Adjacent Sibling Selectors:
- Select elements immediately following another element, sharing the same parent.
- For example,
h1 + p { margin-top: 0; }sets the top margin of the first<p>element immediately after an<h1>to 0.
-
General Sibling Selectors:
- Select all sibling elements following another element, sharing the same parent.
- For example,
h1 ~ p { color: red; }sets the text color of all<p>elements following an<h1>to red.
These selectors can be used individually or combined to achieve complex selection logic, allowing precise control over CSS styling.
2024年8月14日 20:16 回复