1. 从零开始:HTML+CSS动画基础搭建
第一次接触网页动画时,我也曾被那些专业术语吓到。但后来发现,用最基本的HTML和CSS就能创造出让人眼前一亮的动态效果。这个会摇尾巴的小狗动画,就是最好的入门案例。
我们先准备最基础的文件结构。创建一个名为dog-animation的文件夹,里面新建两个文件:index.html和style.css。这种分离结构是前端开发的标准做法,既清晰又便于维护。
在index.html中,我们写入以下基础代码:
html复制<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>可爱小狗动画</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="dog-container">
<!-- 小狗的各个部位将在这里构建 -->
</div>
</body>
</html>
这里有几个关键点需要注意:
<!DOCTYPE html>声明确保浏览器以标准模式渲染页面viewport的meta标签让页面在移动设备上正确缩放- 我们通过
link标签引入了外部CSS文件
在style.css中,我们先设置一些基础样式:
css复制body {
background-color: #f9f3f3; /* 柔和的粉色背景 */
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
overflow: hidden;
}
.dog-container {
position: relative;
width: 300px;
height: 300px;
}
提示:使用
vh(viewport height)单位可以让容器始终占据整个视口高度,这在全屏展示动画时特别有用。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 构建小狗的静态结构
现在我们来绘制小狗的基本形状。我们将使用纯CSS来创建这只可爱的小狗,这需要一些创意和对CSS属性的灵活运用。
2.1 绘制小狗头部
在index.html的dog-container div中添加:
html复制<div class="dog-head"></div>
然后在style.css中添加样式:
css复制.dog-head {
position: absolute;
width: 120px;
height: 100px;
background: #f8a5c2;
border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
top: 50px;
left: 90px;
z-index: 10;
box-shadow: inset -10px -5px 15px rgba(0,0,0,0.1);
}
这里使用了border-radius的高级写法,通过指定水平和垂直方向的不同半径,创造出了更自然的头部形状。box-shadow的inset属性则创造了内阴影效果,让头部看起来更有立体感。
2.2 添加耳朵和面部特征
小狗的耳朵会使用伪元素来实现,这是CSS中非常实用的技巧:
css复制.dog-head::before, .dog-head::after {
content: '';
position: absolute;
width: 30px;
height: 50px;
background: #f8a5c2;
border-radius: 50%;
top: -20px;
}
.dog-head::before {
left: 15px;
transform: rotate(-30deg);
}
.dog-head::after {
right: 15px;
transform: rotate(30deg);
}
眼睛和鼻子可以这样添加:
html复制<div class="dog-eyes">
<div class="eye left-eye"></div>
<div class="eye right-eye"></div>
</div>
<div class="dog-nose"></div>
对应的CSS:
css复制.dog-eyes {
position: absolute;
top: 40px;
width: 100%;
display: flex;
justify-content: space-around;
}
.eye {
width: 20px;
height: 20px;
background: #333;
border-radius: 50%;
position: relative;
}
.eye::after {
content: '';
position: absolute;
width: 8px;
height: 8px;
background: white;
border-radi
