css制作加号
使用伪元素实现加号
通过CSS的::before和::after伪元素可以创建水平和垂直线条组合成加号形状。
.plus-icon {
position: relative;
width: 20px;
height: 20px;
}
.plus-icon::before,
.plus-icon::after {
content: "";
position: absolute;
background-color: black;
}
.plus-icon::before {
width: 100%;
height: 2px;
top: 50%;
transform: translateY(-50%);
}
.plus-icon::after {
width: 2px;
height: 100%;
left: 50%;
transform: translateX(-50%);
}
使用边框实现加号
利用元素的边框属性创建加号,这种方法更简洁。
.plus-border {
width: 20px;
height: 20px;
position: relative;
}
.plus-border::before {
content: "";
position: absolute;
top: 0;
left: 9px;
width: 2px;
height: 100%;
background: black;
}
.plus-border::after {
content: "";
position: absolute;
top: 9px;
left: 0;
width: 100%;
height: 2px;
background: black;
}
使用背景渐变实现加号
CSS线性渐变可以创建精细的加号图形,适合需要平滑过渡的场景。
.plus-gradient {
width: 24px;
height: 24px;
background-image:
linear-gradient(to bottom, transparent 35%, black 35%, black 65%, transparent 65%),
linear-gradient(to right, transparent 35%, black 35%, black 65%, transparent 65%);
}
响应式加号实现
通过相对单位使加号大小随容器变化。
.plus-responsive {
position: relative;
width: 1em;
height: 1em;
}
.plus-responsive::before,
.plus-responsive::after {
content: "";
position: absolute;
background-color: currentColor;
}
.plus-responsive::before {
width: 100%;
height: 0.1em;
top: 50%;
transform: translateY(-50%);
}
.plus-responsive::after {
width: 0.1em;
height: 100%;
left: 50%;
transform: translateX(-50%);
}
动画加号效果
为加号添加悬停动画增强交互体验。
.plus-animate {
width: 30px;
height: 30px;
position: relative;
transition: transform 0.3s ease;
}
.plus-animate::before,
.plus-animate::after {
content: "";
position: absolute;
background-color: blue;
transition: all 0.3s ease;
}
.plus-animate::before {
width: 100%;
height: 3px;
top: 50%;
transform: translateY(-50%);
}
.plus-animate::after {
width: 3px;
height: 100%;
left: 50%;
transform: translateX(-50%);
}
.plus-animate:hover {
transform: rotate(90deg);
}
.plus-animate:hover::before {
background-color: red;
}
.plus-animate:hover::after {
background-color: red;
}
每种实现方式都有其适用场景,伪元素方法最灵活,边框方法最简单,渐变方法适合复杂背景,响应式方案适配不同设备,动画方案增强用户体验。可根据具体需求选择合适的技术方案。







