为按钮元素添加before伪元素,想让伪元素宽高与按钮一致,设置100%后发现伪元素宽高与窗口相同,如何设置才能使其宽高与按钮一致?
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<style>
.animated{
padding: 5px 10px;
border: 1px solid #f08c41;
color: #f08c41;
background-color: white;
}
.animated::before{
content: "";
background-color: #f08c41;
display: block;
position: absolute;
width: 100%;
height: 100%;
z-index: 5;
}
style>
head>
<body>
<button class="animated">Contact Us Now!button>
body>
html>
该回答引用GPTᴼᴾᴱᴺᴬᴵ
您可以尝试将按钮的 position 属性设置为 relative,然后将伪元素的 position 属性设置为 absolute,并使用 top 和 left 属性将伪元素定位在按钮的上方。然后设置伪元素的宽度和高度为 100%。最后,将伪元素的 z-index 属性设置为 -1,使其在按钮下方。
以下是修改后的代码示例:
<style>
.animated{
position: relative;
padding: 5px 10px;
border: 1px solid #f08c41;
color: #f08c41;
background-color: white;
}
.animated::before{
content: "";
background-color: #f08c41;
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
</style>
这样可以确保伪元素的宽高与按钮一致,并且伪元素可以在按钮下面。