如何使用styled-components实现圆形按钮内嵌方形的样式效果
圆形按钮内嵌方形效果实现方案
实现逻辑
- 给按钮添加
border-radius: 50%属性实现外层圆形效果 - 用
::before伪元素生成内部方形,无需额外新增DOM节点 - 调整伪元素尺寸、颜色即可匹配设计需求
styled-components 实现代码
const ButtonCircle = styled.button` background: red; height: 60px; width: 60px; color: white; padding: 1rem; border: none; cursor: pointer; font-size: 27px; border: 5px solid white; /* 新增圆形属性 */ border-radius: 50%; position: relative; display: inline-flex; align-items: center; justify-content: center; /* 内部方形实现 */ &::before { content: ''; position: absolute; /* 可自定义方形大小 */ width: 30px; height: 30px; /* 可自定义方形颜色 */ background: white; } /* 若有内部内容,加z-index避免被伪元素遮挡 */ > * { position: relative; z-index: 1; } `;
原生CSS实现代码
.btn-circle { background: red; height: 60px; width: 60px; color: white; padding: 1rem; border: none; cursor: pointer; font-size: 27px; border: 5px solid white; border-radius: 50%; position: relative; display: inline-flex; align-items: center; justify-content: center; } .btn-circle::before { content: ''; position: absolute; width: 30px; height: 30px; background: white; } .btn-circle > * { position: relative; z-index: 1; }
内容的提问来源于stack exchange,提问作者Gray Singh
相关产品推荐
相关产品推荐

