解决hover显示边框时发生抖动的问题

当我们用 :hover 选择器的时候,如果要给鼠标滑过的元素加上边框或者加粗边框的时候,有可能会发生抖动现象(甚至有可能会挤走下面的元素),见下图:

hover显示边框抖动现象录屏

解决方法:

方法一:提前加边框。给元素加上 n像素(想要hover的时候显示多少像素边框就加多少像素) 的和背景色一样的边框(或者干脆将border的透明度为0,eg: border:1px solid rgba(100,100,100,0) ),hover的时候改变边框颜色(和透明度)即可

提前加边框

//html			
<section class="hidn">
    <ul>
	    <li>立即购买</li>
		<li>加入购物车</li>
		<li>收藏</li>
	</ul>
</section>
//css:		
			    .hidn{
				position: absolute;
				width: 330px;
				height:310px;
				top: 0px;
				left: 0px;
				background-color: rgb(100,100,100);
				
			}
			.hidn ul{
				margin-top: 50px;
			}
			.hidn ul li{
				background-color: yellow;
				border: 2px solid rgb(100,100,100); //!!!!!!!!!!
				width: 160px;
				height: 40px;
				line-height: 40px;
				text-align: center;
				padding: 10px;
				list-style: none;
				margin:10px 74px;
				
			}
			.hidn ul li:hover{
				border: 2px solid rgb(255,255,255); //!!!!!!!!!!
			}

方法二:用padding替边框先占位,hover的时候再将位置还给边框(让padding与边框的值此消彼长)。也就是说加入我原本边框为0,我想实现当hover的时候边框为3px且不抖动,就可以先设置一个3px的padding;hover的时候,padding设为0,border设为3px。

用padding替边框先占位

.hidn ul li{
    background-color: yellow;
	/*border: 2px solid rgba(100,100,100);一开始不设边框 */
	width: 160px;
	height: 40px;
	line-height: 40px;
	text-align: center;
	padding: 12px;   /*padding: 10px; 本来我想要padding为10的,我想要hover时border为2,故padding设为10+2=12 */
	list-style: none;
	margin:10px 74px;
				
	}
	.hidn ul li:hover{
	border: 2px solid rgb(255,255,255); /*border为2*/
	padding: 10px;   /*padding重新设为10*/
	}

猜你喜欢

转载自blog.csdn.net/hst_gogogo/article/details/90812564