选择器
优先级: id
选择器 > 类选择器 > 标签选择器
类选择器:
.myClass {color: blue;
}
id
选择器(全局唯一):
#myId {color: green;
}
标签选择器:
p {color: red;
}
层次选择器:
.nav a {color: blue;
}
.card > h2 {color: red;
}
h1 + p {font-size: 20px;
}
h1 ~ p {color: gray;
}
伪类选择器:
伪类选择器 | 作用 |
---|
:hover | 鼠标悬停时触发 |
:focus | 元素获得焦点时触发(如 input ) |
:first-child | 选择父元素的第一个子元素 |
:last-child | 选择父元素的最后一个子元素 |
:nth-child(n) | 选择第 n 个子元素 |
:nth-of-type(n) | 选择第 n 个特定类型的子元素 |
:checked | 选择被选中的单选框/复选框 |
:disabled | 选择禁用的表单元素 |
属性选择器:
选择器 | 作用 | 示例 |
---|
[attr] | 选择包含某个属性的元素 | input[required] |
[attr=value] | 选择属性值等于某个值的元素 | input[type="text"] |
[attr~=value] | 选择属性值中包含某个单词的元素 | [class~="btn"] |
[attr^=value] | 选择属性值以某个字符串开头的元素 | a[href^="https"] |
[attr$=value] | 选择属性值以某个字符串结尾的元素 | a[href$=".pdf"] |
[attr*=value] | 选择属性值中包含某个字符串的元素 | input[name*="user"] |
示例:
a[target="_blank"] {color: red;
}
a[href^="https"] {color: green;
}
CSS 的引入方式(优先级:就近原则)
<p style="color: red; font-size: 16px;">天津科技大学</p>
<!DOCTYPE html>
<html>
<head><style>p {color: blue;font-size: 18px;}</style>
</head>
<body><p>天津科技大学</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head><link href="styles.css" rel="stylesheet">
</head>
<body><p>what are you doing.</p>
</body>
</html>
styles.css
内容:
p {color: green;font-size: 20px;
}
盒子模型
组成:
content
(内容区域) - 盒子的实际内容,如文本、图片等。padding
(内边距) - 内容与边框之间的间距,影响背景颜色的填充范围。border
(边框) - 围绕内容和内边距的边界线,可设置颜色、样式和宽度。margin
(外边距) - 盒子与相邻元素之间的间距,不影响背景颜色。
结构示意图:
+-------------------------------+
| margin | 外边距
| +-------------------------+ |
| | border | | 边框
| | +-------------------+ | |
| | | padding | | | 内边距
| | | +-----------+ | | |
| | | | content | | | | 内容
| | | +-----------+ | | |
| | +-------------------+ | |
| +-------------------------+ |
+-------------------------------+
相关属性:
属性 | 作用 | 示例 |
---|
width | 盒子内容区域(content)的宽度 | width: 200px; |
height | 盒子内容区域(content)的高度 | height: 100px; |
padding | 内边距(content 到 border) | padding: 10px; |
border | 边框(border) | border: 2px solid black; |
margin | 外边距(margin) | margin: 20px; |
HTML 嵌套规范注意点:
- 块级元素 可嵌套文本、块级元素、行内元素,但
p
标签中不能嵌套 div
、p
、h
等块级元素。 a
标签 内部可以嵌套任意元素,但不能嵌套 a
标签。