我想了解CSS中的悬停效果。我创建了4个按钮,并填充蓝色#3498db作为背景色。不幸的是,我不明白为什么使用 content:""
和 left:0px
填充按钮框的一半。
Html代码 -
<body>
<div class="buttonbox">
<button class="btn btn1">Hover me!</button>
<button class="btn btn2">Hover me!</button>
<button class="btn btn3">Hover me!</button>
<button class="btn btn4">Hover me!</button>
</div>
</body>
CSS代码 -
.btn{
padding: 10px;
margin: 30px;
border: 1px solid #3498db;
font-family: sans-serif;
width: 100px;
background: none;
cursor: pointer;
position: relative;
overflow: hidden;
}
.btn::before{
position: absolute;
content: "";
left:0;
z-index: -1;
width: 100%;
height: 100%;
background-color: #3498db;
}
.btn1, .btn2{
color: #3498db;
transition: all .5s;
}
.btn3, .btn4{
color: #fff;
transition: all .5s;
}
.btn1:hover, .btn2:hover{
color: #fff;
}
.btn3:hover, .btn4:hover{
color: #3498db;
}
只需添加 top: 0;
到 .btn::before
. 如果一个绝对定位元素的X和Y位置缺失,它就会被放置在正常的位置上,这就是 不 设置为0(这有时会很有用,尽管不设置X和Y位置而使用绝对定位不是很常见)。content: ""
对于伪元素的前后是必要的--否则,它就不存在了(尝试在浏览器的开发工具中删除该属性,它会消失)。
检查css内容属性 针对这种情况。
你的css代码的困惑是。我认为你需要设置.btn类的bg颜色,而不是btn::before。因为::before在添加一个新的项目时,会设置它的bg颜色,而如果你在content属性中设置一个字符串,它就会把这个字符串添加到相关项目之前。
看看我下面的代码。我删除了按钮的内部文本,并通过::before内容属性来设置它们。
.btn{
padding: 10px;
margin: 30px;
border: 1px solid #3498db;
font-family: sans-serif;
width: 100px;
height: 40px;
background: none;
cursor: pointer;
position: relative;
overflow: hidden;
background-color: #3498db;
border-radius: 3px;
}
.btn::before{
position: absolute;
content: "Hover me!";
left:0;
width: 100%;
height: 100%;
top:12px;
}
.btn1, .btn2{
color: #3498db;
transition: all .5s;
}
.btn3, .btn4{
color: #fff;
transition: all .5s;
}
.btn1:hover, .btn2:hover{
color: #fff;
}
.btn3:hover, .btn4:hover{
color: #3498db;
}
<body>
<div class="buttonbox">
<button class="btn btn1"></button>
<button class="btn btn2"></button>
<button class="btn btn3"></button>
<button class="btn btn4"></button>
</div>
</body>
你可以只使用
background-size: cover