-
通用选择器
*:选择所有元素。
* {margin: 0;padding: 0; } -
类型选择器
- 选择所有指定类型的HTML元素。
p {color: blue; } -
类选择器
className:选择所有具有指定类名的元素。
.highlight {background-color: yellow; } -
ID选择器
#idName:选择具有指定ID的元素。
#header {font-size: 2em; } -
属性选择器
[attribute]:选择具有指定属性的元素。
[type="text"] {border: 1px solid gray; } -
伪类选择器(
:hover:鼠标悬停在元素上。
a:hover {color: red; }:focus:元素获得焦点。
input:focus {border-color: blue; }:nth-child():选择其父元素的特定子元素。
li:nth-child(2) {font-weight: bold; } -
伪元素选择器
::before和::after:在元素的内容前后添加装饰性内容。
div::before {content: "Before";color: green; } div::after {content: "After";color: green; } -
后代选择器
ancestor descendant:选择作为祖先元素后代的元素。
.container p {font-family: Arial, sans-serif; } -
子代选择器
parent > child:选择作为指定父元素直接子代的元素。
ul > li {list-style-type: none; } -
相邻兄弟选择器
element1 + element2:选择紧随在指定元素之后的相邻兄弟元素。
h1 + p {font-size: 1.2em; } -
通用兄弟选择器
element1 ~ element2:选择所有跟随在指定元素之后的兄弟元素。
h2 ~ p {color: gray; } -
选择器组合:
- 可以将多个选择器组合起来以更精确地选择元素。
#main ul li.active {color: white; }
这些是CSS中常用的选择器,通过它们可以针对不同的HTML元素应用样式。CSS的属性则更多,包括字体、颜色、布局、视觉效果等各个方面的设置。掌握这些选择器和属性的使用,是进行网页样式设计的基础。