css
526字约2分钟
前端CSS样式
2024-11-16
一、CSS 基本概念
1. CSS 语法
基本结构
selector { property: value; }示例
p { color: blue; font-size: 16px; }
2. 引入 CSS
内联样式
<p style="color: blue;">This is a paragraph.</p>内部样式表
<style> p { color: blue; } </style>外部样式表
<link rel="stylesheet" href="styles.css">
二、选择器
1. 基本选择器
元素选择器
h1 { color: red; }类选择器
.class-name { font-weight: bold; }ID 选择器
#unique-id { text-align: center; }
2. 组合选择器
后代选择器
div p { color: green; }子选择器
ul > li { margin: 5px; }相邻兄弟选择器
h1 + p { margin-top: 10px; }
3. 属性选择器
存在属性选择器
a[href] { color: orange; }特定属性选择器
input[type="text"] { border: 1px solid #ccc; }
三、常用样式属性
1. 文本样式
字体和文本
body { font-family: Arial, sans-serif; font-size: 14px; line-height: 1.5; color: #333; }文本对齐和装饰
h1 { text-align: center; text-decoration: underline; }
2. 背景和边框
背景
body { background-color: #f0f0f0; background-image: url('background.jpg'); background-size: cover; }边框
div { border: 1px solid #000; border-radius: 5px; }
3. 盒模型
内边距和外边距
.box { padding: 10px; margin: 20px; }宽度和高度
.container { width: 80%; max-width: 1200px; height: 400px; }
四、布局
1. 浮动布局
使用浮动
.column { float: left; width: 50%; }清除浮动
.clearfix::after { content: ""; display: table; clear: both; }
2. Flexbox 布局
弹性容器
.flex-container { display: flex; justify-content: space-between; align-items: center; }弹性项目
.flex-item { flex: 1; margin: 10px; }
3. 网格布局
网格容器
.grid-container { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }网格项目
.grid-item { background-color: #ccc; padding: 20px; }
五、响应式设计
1. 媒体查询
基本媒体查询
@media (max-width: 768px) { body { background-color: lightblue; } }响应式布局
.responsive { width: 100%; max-width: 600px; }
六、CSS3 新特性
1. 过渡和动画
过渡效果
.button { transition: background-color 0.3s; } .button:hover { background-color: #555; }关键帧动画
@keyframes slidein { from { transform: translateX(-100%); } to { transform: translateX(0); } } .animated { animation: slidein 2s; }
2. 阴影和渐变
盒阴影
.box { box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); }文本阴影
h1 { text-shadow: 2px 2px 4px #aaa; }线性渐变
.gradient { background: linear-gradient(to right, red, yellow); }
