css方块制作
使用 div 元素创建基础方块
在 HTML 中创建一个 <div> 元素,通过 CSS 设置其宽度、高度和背景色即可形成基础方块。示例代码如下:
<div class="square"></div>
.square {
width: 100px;
height: 100px;
background-color: #3498db;
}
添加边框和圆角
通过 border 属性为方块添加边框,使用 border-radius 实现圆角效果。以下代码展示了一个带圆角的蓝色方块:
.square {
width: 100px;
height: 100px;
background-color: #3498db;
border: 2px solid #2980b9;
border-radius: 10px;
}
实现悬停动画效果
结合 CSS 过渡(transition)和伪类(:hover)实现交互效果。以下示例使方块在悬停时放大并改变颜色:
.square {
width: 100px;
height: 100px;
background-color: #3498db;
transition: all 0.3s ease;
}
.square:hover {
transform: scale(1.1);
background-color: #e74c3c;
}
使用伪元素创建复杂形状
通过 ::before 或 ::after 伪元素叠加更多样式。以下代码在方块内部添加了一个白色十字:
.square {
width: 100px;
height: 100px;
background-color: #3498db;
position: relative;
}
.square::before, .square::after {
content: '';
position: absolute;
background-color: white;
}
.square::before {
width: 60%;
height: 10px;
top: 45%;
left: 20%;
}
.square::after {
width: 10px;
height: 60%;
top: 20%;
left: 45%;
}
响应式方块设计
使用 vw 或百分比单位实现自适应大小。以下代码创建了一个始终占据视口宽度 20% 的方块:

.square {
width: 20vw;
height: 20vw;
background-color: #3498db;
max-width: 200px;
max-height: 200px;
}






