css 制作
使用 CSS 制作样式
CSS(层叠样式表)用于控制网页的外观和布局。通过 CSS 可以定义字体、颜色、间距、背景等样式属性。
内联样式
直接在 HTML 元素的 style 属性中编写 CSS:
<p style="color: blue; font-size: 16px;">这是一段蓝色文字。</p>
内部样式表
在 HTML 文件的 <head> 部分使用 <style> 标签定义样式:
<style>
p {
color: blue;
font-size: 16px;
}
</style>
外部样式表
将 CSS 代码保存在单独的 .css 文件中,并通过 <link> 标签引入:
<link rel="stylesheet" href="styles.css">
styles.css 文件内容:

p {
color: blue;
font-size: 16px;
}
常见 CSS 属性
文本样式
控制文字的颜色、大小、对齐方式等:
p {
color: #333;
font-family: Arial, sans-serif;
font-size: 14px;
text-align: center;
line-height: 1.5;
}
盒模型
设置元素的边距、边框和内边距:
div {
width: 200px;
height: 100px;
margin: 10px;
padding: 15px;
border: 1px solid #ccc;
}
背景与渐变
定义背景颜色、图片或渐变效果:

body {
background-color: #f4f4f4;
background-image: url('bg.jpg');
background-repeat: no-repeat;
}
.gradient {
background: linear-gradient(to right, #ff7e5f, #feb47b);
}
布局技术
Flexbox
创建灵活的布局结构:
.container {
display: flex;
justify-content: space-between;
align-items: center;
}
.item {
flex: 1;
}
Grid
实现复杂的网格布局:
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
gap: 10px;
}
.grid-item {
grid-column: span 1;
}
响应式设计
使用媒体查询适配不同设备:
@media (max-width: 768px) {
.container {
flex-direction: column;
}
.grid-container {
grid-template-columns: 1fr;
}
}
动画与过渡
添加交互效果:
.button {
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #4CAF50;
}
@keyframes slide {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}
.slider {
animation: slide 2s infinite alternate;
}
最佳实践
- 使用语义化的类名(如
.header而非.div1) - 避免过度嵌套选择器
- 优先使用 Flexbox/Grid 替代浮动布局
- 通过变量维护主题色等重复值:
:root { --primary-color: #4285f4; } .button { background-color: var(--primary-color); }
以上内容涵盖了 CSS 的核心功能和使用方法,从基础样式定义到高级布局技术,可根据具体需求选择适合的实现方式。






