纯css制作相册
纯CSS制作相册的方法
使用Flexbox布局
通过Flexbox可以轻松实现相册的响应式排列。定义一个容器,设置display: flex和flex-wrap: wrap,使项目自动换行。每个相册项目设置固定宽度和边距,确保在不同屏幕尺寸下整齐排列。
.photo-gallery {
display: flex;
flex-wrap: wrap;
gap: 10px;
padding: 10px;
}
.photo-item {
flex: 1 1 200px;
height: 200px;
overflow: hidden;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.photo-item img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.photo-item:hover img {
transform: scale(1.05);
}
使用CSS Grid布局
CSS Grid提供了更灵活的布局选项,可以精确控制行列分布。定义一个网格容器,设置grid-template-columns为重复的自适应列,通过gap属性调整间距。

.photo-gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 15px;
padding: 15px;
}
.photo-item {
position: relative;
overflow: hidden;
aspect-ratio: 1 / 1;
border-radius: 8px;
}
.photo-item img {
width: 100%;
height: 100%;
object-fit: cover;
transition: opacity 0.3s;
}
.photo-item:hover img {
opacity: 0.8;
}
添加悬停效果
通过CSS过渡和变换增强交互体验。常见的悬停效果包括放大图片、显示标题或叠加层。使用transition平滑动画,结合transform实现缩放或位移。

.photo-item::after {
content: attr(data-title);
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.7);
color: white;
padding: 10px;
transform: translateY(100%);
transition: transform 0.3s;
}
.photo-item:hover::after {
transform: translateY(0);
}
实现灯箱效果
纯CSS灯箱通过:target伪类实现。点击缩略图时,显示全尺寸图片和背景遮罩。利用position: fixed将灯箱覆盖整个视口,通过z-index控制层级。
.lightbox {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
display: none;
z-index: 100;
}
.lightbox:target {
display: flex;
align-items: center;
justify-content: center;
}
.lightbox img {
max-width: 90%;
max-height: 90%;
border: 3px solid white;
}
响应式调整
通过媒体查询优化不同设备的显示效果。在小屏幕上减少列数或调整图片尺寸,确保内容可读性和操作便利性。
@media (max-width: 600px) {
.photo-gallery {
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
}






