颜色与背景
颜色是网页视觉的第一要素。CSS 中颜色可以使用关键字(red)、十六进制(#ff0000)、rgb/rgba、hsl 等方式表示。
颜色表示法
#ff0000:十六进制,最常用;rgb(255, 0, 0):红绿蓝三通道;rgba(255, 0, 0, 0.5):带透明度(0-1);hsl(0, 100%, 50%):色相-饱和度-明度。
背景属性
background-color 设置背景色;background-image 设置背景图;background-size: cover 让背景图铺满容器;background: linear-gradient(...) 可设置渐变背景。
代码示例
<style>
.box {
width: 300px;
height: 150px;
/* 渐变背景 */
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
/* 圆角与内边距 */
border-radius: 12px;
padding: 20px;
color: #fff;
}
.half {
/* 半透明背景 */
background: rgba(0, 0, 0, 0.3);
padding: 8px;
border-radius: 6px;
}
</style>
<div class="box">
<div class="half">渐变背景 + 半透明遮罩</div>
</div>
📚 CSS 属性速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
color: #333; | 文字颜色 |
background: #fff; | 背景色 / 背景图 |
font-size: 16px; | 字号 |
font-family: Arial; | 字体 |
font-weight: bold; | 字重(加粗) |
margin: 10px; | 外边距(上右下左) |
padding: 10px; | 内边距 |
border: 1px solid #ccc; | 边框:粗细 样式 颜色 |
border-radius: 8px; | 圆角 |
width: 100%; | 宽度 |
height: 200px; | 高度 |
display: flex; | 弹性布局(现代布局主力) |
display: none; | 隐藏元素 |
position: relative / absolute / fixed; | 定位方式 |
top / left / right / bottom | 定位偏移 |
text-align: center; | 文字水平对齐 |
line-height: 1.6; | 行高 |
overflow: hidden; | 内容溢出处理 |
box-shadow: 0 2px 8px rgba(0,0,0,.1); | 阴影 |
transition: all .3s; | 过渡动画 |
cursor: pointer; | 鼠标手型 |
z-index: 10; | 层叠顺序 |
max-width: 1200px; margin: 0 auto; | 容器居中(经典写法) |
@media (max-width: 768px) {} | 响应式断点 |
:hover | 鼠标悬停状态 |