今天在学习CSS3时,看到了一个比较有趣的效果:按钮有背景色,鼠标悬停时,背景色变为白色,并且有和原来背景色一样的边框。
在vscode上自己码代码时发现了问题:悬停时会影响的其他元素的位置,即按钮之后的元素,会在鼠标悬停在按钮时,位置向下移动。
经过检查发现,因为我的按钮边框是在悬停效果时加的,在CSS3的默认情况下,该按钮元素会在原来的宽度,高度基础上再加上边框的粗细,从而改变了该元素的大小,影响了其他元素的布局。
解决方法:
一、按钮元素添加声明box-sizing:border-box
该声明允许元素width 和 height 属性中包含了 padding(内边距) 和 border(边框)。即声明了高度和宽度后,再改变边框和内边距,是不会影响这个元素的实际大小的。但这个方法有个不便之处,要计算内边距以及元素的width和height。
二、元素声明边框,但边框透明。之后在:hover添加边框即可。一开始我们就声明了一个透明的边框,后来只是改变边框颜色而已,所以不会增加额外的大小。
代码:
方法一
button.button_color {
position: absolute;
left: 45%;
border-radius: 5px;
background-color: #4caf50;
font-size: 16px;
text-align: center;
padding: 14px 25px;
color: white;
transition-duration: 0.4s;
cursor: pointer;
width: 93px; /*宽度*/
height: 50px; /*高度*/
box-sizing: border-box; /*box-sizing*/
}
button.button_color:hover {
border: 1px solid #4caf50;
background-color: white;
color: black;
}
方法二
button.button_color {
position: absolute;
left: 45%;
border-radius: 5px;
background-color: #4caf50;
font-size: 16px;
text-align: center;
padding: 14px 25px;
color: white;
transition-duration: 0.4s;
cursor: pointer;
border: 1px solid rgba(0, 0, 0, 0); /*设置边框为透明*/
}
button.button_color:hover {
border: 1px solid #4caf50;
background-color: white;
color: black;
}