CSS伪元素样式冲突如何实现按钮左右两侧同时显示丝带角标
问题原因
单个DOM元素最多仅支持同时挂载::before、::after两个伪元素。当前两段CSS规则重复定义了.jumbotron_text .btn的:before伪元素样式,根据CSS层叠规则,后声明的同选择器样式会覆盖前序配置,因此最终仅能渲染单侧角标。
修复步骤
- 给
.jumbotron_text .btn按钮本身添加position: relative属性,作为内部绝对定位伪元素的定位参照物,避免角标位置偏移 - 将右侧丝带角标的样式绑定到
:before伪元素,左侧丝带角标的样式绑定到:after伪元素,两个伪元素独立渲染,不会出现样式覆盖问题
修复后完整CSS代码
.jumbotron_text .btn { position: relative; } .jumbotron_text .btn:before { content: ''; position: absolute; right: -11px; top: 5px; width: 9px; height: 25px; background-image: url(../images/jumbotron_ribbon.png); background-repeat: no-repeat; background-position: top right; background-color: #505050; transition: all 0.3s ease-in-out; -webkit-transition: all 0.3s ease-in-out; } .jumbotron_text .btn:after { content: ''; position: absolute; left: -11px; top: 5px; width: 9px; height: 25px; background-image: url(../images/jumbotron_ribbon_left.png); background-repeat: no-repeat; background-position: top right; background-color: #505050; transition: all 0.3s ease-in-out; -webkit-transition: all 0.3s ease-in-out; }
原有HTML结构不需要做任何修改,替换上述CSS后即可实现按钮双侧同时显示丝带角标的效果。
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

