要创建一个不使用元素覆盖文本的CSS按钮过渡效果,可以使用伪元素
::before
和::after
来实现。以下是一个示例代码:
HTML:
CSS:
.button {
position: relative;
display: inline-block;
padding: 10px 20px;
font-size: 16px;
text-align: center;
text-decoration: none;
border: none;
background-color: #007bff;
color: #fff;
cursor: pointer;
transition: background-color 0.3s;
}
.button::before,
.button::after {
content: "";
position: absolute;
top: 0;
bottom: 0;
width: 50%;
background-color: inherit;
z-index: -1;
transition: width 0.3s;
}
.button::before {
left: 0;
}
.button::after {
right: 0;
}
.button:hover {
background-color: #0056b3;
}
.button:hover::before {
width: 100%;
}
.button:hover::after {
width: 100%;
}
在这个示例中,我们创建了一个按钮类.button
,它具有基本的样式。通过使用伪元素::before
和::after
,我们可以创建两个覆盖整个按钮的元素,并将它们的宽度设置为50%。当鼠标悬停在按钮上时,我们通过将伪元素的宽度设置为100%来实现过渡效果。
请注意,::before
和::after
的content
属性被设置为空字符串,这是必需的,以便伪元素显示出来。另外,我们将伪元素的z-index
属性设置为-1,以确保它们位于按钮的下面。
这样,我们就创建了一个没有使用覆盖文本的CSS按钮过渡效果。