我尝试了很多方法在图像元素上放置线性渐变,但没有任何效果!
我尝试使用 z-index 并询问聊天 gpt,但两者都没有帮助。你能帮我解释一下为什么它不起作用吗?
div {
background: linear-gradient(180deg, black, transparent);
width: 100%;
height: 1000px;
z-index: 2;
}
img {
z-index: 1;
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<div class="mydiv">
<img src="https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1">
</div>
</body>
</html>
刚刚稍微编辑了您的示例。您需要将图像移到 div 之外,并将 div 放置在图像上方。使用下面的示例并根据需要进行修改。
div{
background: linear-gradient(180deg, black, transparent
);
width: 200px;
height: 200px;
z-index: 2;
position: absolute;
top: 0px;
left: 0px;
}
img{
width: 200px;
height: 200px;
z-index: 1;
position: absolute;
top: 0px;
left: 0px;
}
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
</head>
<body>
<img src="https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1">
<div class=“mydiv”></div>
</body>
</html>
试试这个
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-
scale=1.0"
/>
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
.mydiv {
position: absolute;
background: linear-gradient(180deg, black, transparent);
width: 100%;
height: 100vh;
z-index: 1;
}
img {
position: absolute;
}
</style>
</head>
<body>
<div class="mydiv"></div>
<img
src="https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
/>
</body>
</html>