前几天某个同事的项目中碰到一个边框重叠鼠标悬停效果,要实现鼠标移上后按钮边框换色,但左右两个按钮的边框又是合并在一起的。就像下面这张图片示意:
如果看不明白,请移步参考淘宝搜索结果页面中的“信用”、“价格”两个排序按钮。http://s.taobao.com/search?q=%CC%D4%B1%A6
以三个横排并列的按钮为例:
<span class="grid"> <a href="#">A</a> <a href="#">B</a> <a href="#">C</a> </span>
这个问题的关键在于合并相邻两个容器的边框,视觉上就像表格边框的合并那样,芒果选择使用负 margin 来隐藏右侧边框。鼠标 hover 时如何才能使当前按钮边框呈现出来?其实也很简单,只要给 a:hover 伪类加上 position:relative;z-index:1; 即可。另外,为了修复 IE6 下的定位问题,建议给每一个 a 元素添加 position:relative; 属性。样式代码如下:
.grid{display:inline-block;} .grid a{float:left;border:5px solid #cdcdcd;margin-right:-5px;position:relative;width:50px;height:50px;line-height:50px;text-align:center;} .grid a:hover{border:5px solid #31b1fc;position:relative;z-index:1;}
最终效果如下。因为子节点浮动,外层最好能清除浮动,清浮动的方法请猛击此处查看:http://www.mangguo.org/mangguo-teach-you-clear-float
另外,芒果还想到一种形如九宫格的 CSS 实现,代码也很简洁。
详情参考这份 DEMO 稿:http://www.mangguo.org/example/border_collapse_hover.html