CSS(层叠样式表)是用于控制网页样式和布局的语言。以下是一些常用的CSS属性及其用法示例:
1. 颜色和背景
color: 设置文本颜色。background-color: 设置元素的背景颜色。background-image: 设置元素的背景图像。
p {
color: #333; /* 设置文本颜色为深灰色 */
background-color: #f8f8f8; /* 设置背景颜色为浅灰色 */
background-image: url('path/to/image.jpg'); /* 设置背景图像 */
}
2. 字体样式
font-family: 设置字体类型。font-size: 设置字体大小。font-weight: 设置字体粗细。
body {
font-family: Arial, sans-serif; /* 设置默认字体 */
font-size: 16px; /* 设置默认字体大小 */
}
h1 {
font-weight: bold; /* 设置标题为粗体 */
}
3. 布局
display: 定义元素的显示类型。width和height: 设置元素的宽度和高度。margin和padding: 设置元素的外边距和内边距。
.container {
width: 80%; /* 设置容器宽度为80% */
margin: 0 auto; /* 上下为0,左右自动(居中) */
padding: 20px; /* 设置内边距为20px */
}
.hidden {
display: none; /* 隐藏元素 */
}
4. 边框
border: 设置元素的边框。border-width: 设置边框宽度。border-style: 设置边框样式(如solid,dashed,dotted)。border-color: 设置边框颜色。
.box {
border: 2px solid #000; /* 设置边框为2px实线黑色 */
border-radius: 8px; /* 设置边框圆角 */
}
5. 列表
list-style-type: 设置列表项前的标记类型(如disc,circle,square,none)。
ul {
list-style-type: none; /* 移除列表项前的标记 */
}
6. 链接
text-decoration: 设置文本的装饰(如underline,overline,line-through,none)。
a {
text-decoration: none; /* 移除链接的下划线 */
color: blue; /* 设置链接颜色为蓝色 */
}
7. 定位
position: 设置元素的定位方式(如static,relative,absolute,fixed,sticky)。top,right,bottom,left: 设置元素相对于其正常位置或父元素的偏移。
.fixed-element {
position: fixed; /* 固定定位 */
bottom: 0;
right: 0;
}
8. 响应式设计
@media: 用于创建响应式设计,根据不同屏幕尺寸应用不同的样式。
@media (max-width: 600px) {
body {
font-size: 14px; /* 在屏幕宽度小于600px时,字体大小调整为14px */
}
}
9. 动画
transition: 设置元素的过渡效果。animation: 设置元素的动画效果。
button {
transition: background-color 0.3s; /* 背景颜色变化有0.3秒的过渡效果 */
}
button:hover {
background-color: #555; /* 鼠标悬停时背景颜色变为深灰色 */
}