css制作加号按钮
使用伪元素创建加号按钮
通过CSS伪元素(::before和::after)可以高效地绘制加号形状。核心思路是创建一个水平条和一个垂直条叠加形成加号。
.plus-button {
width: 40px;
height: 40px;
position: relative;
background-color: #3498db;
border-radius: 4px;
cursor: pointer;
}
.plus-button::before,
.plus-button::after {
content: "";
position: absolute;
background-color: white;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.plus-button::before {
width: 60%;
height: 4px;
}
.plus-button::after {
width: 4px;
height: 60%;
}
使用边框实现加号效果
通过控制边框宽度和元素尺寸,可以直接用CSS边框绘制加号。这种方法适合需要简单图标的场景。
.plus-icon {
width: 20px;
height: 20px;
position: relative;
}
.plus-icon::before {
content: "";
position: absolute;
top: 0;
left: 50%;
width: 0;
height: 100%;
border-left: 2px solid black;
}
.plus-icon::after {
content: "";
position: absolute;
top: 50%;
left: 0;
width: 100%;
height: 0;
border-top: 2px solid black;
}
结合SVG的响应式加号
使用内联SVG可以创建分辨率无关的加号按钮,适合需要高清晰度的场景。
<button class="svg-plus">
<svg viewBox="0 0 24 24" width="24" height="24">
<path d="M12 4V20M4 12H20" stroke="currentColor" stroke-width="2"/>
</svg>
</button>
.svg-plus {
width: 48px;
height: 48px;
background: #2ecc71;
border: none;
border-radius: 50%;
color: white;
padding: 12px;
}
动画增强的加号按钮
为加号按钮添加悬停动画可以提升用户体验,以下示例实现旋转和颜色变化效果。
.animated-plus {
width: 50px;
height: 50px;
background: #e74c3c;
position: relative;
transition: all 0.3s ease;
}
.animated-plus:hover {
background: #c0392b;
transform: rotate(90deg);
}
.animated-plus::before,
.animated-plus::after {
content: "";
position: absolute;
background: white;
transition: all 0.3s ease;
}
.animated-plus::before {
width: 60%;
height: 8%;
left: 20%;
top: 46%;
}
.animated-plus::after {
width: 8%;
height: 60%;
left: 46%;
top: 20%;
}
使用Flexbox居中加号
当需要将加号完美居中在按钮内部时,Flexbox布局是最简洁的解决方案。
.flex-plus {
width: 64px;
height: 64px;
background: #9b59b6;
display: flex;
justify-content: center;
align-items: center;
border-radius: 50%;
}
.flex-plus span {
position: relative;
width: 30px;
height: 30px;
}
.flex-plus span::before,
.flex-plus span::after {
content: "";
position: absolute;
background: white;
}
.flex-plus span::before {
width: 100%;
height: 4px;
top: 13px;
}
.flex-plus span::after {
width: 4px;
height: 100%;
left: 13px;
}






