CSS - 图像周围的背景颜色,带有一些透明像素



>我有一个固定大小的图像,其中一部分是透明的,我目前将其用作DIV背景。我必须将图像精确地放置在屏幕中心

问题是我需要图像周围的所有空间都是黑色的。如果我用background: black url(...设置它 - 图像的透明像素也会变成黑色,这是错误的。

另一个问题是网站内容是动态的,所以我不能用 2 个具有相同背景图像和不同过滤器的 DIV 作弊。我需要清楚地查看透明像素。

我当前的代码:

<html>
<head>
<style>
.image {
height: 100%;
background: black url(image.png) center center no-repeat;
background-size: auto 100%;
}   
</style>
</head>
<body>
<div class="image"></div>
</body>
</html>

简而言之 - 我需要通过图像的透明部分查看内容,屏幕的另一部分必须是黑色的。我如何实现这一点?

我建议一个巨大的盒子阴影;

body {
background: pink;
display: flex;
height: 100vh;
}
.wrap {
height: 200px;
width: 200px;
border: 1px solid green;
margin: auto;
background-image: url(https://www199.lunapic.com/editor/premade/transparent.gif);
background-size: 200px;
background-repeat: no-repeat;
background-position: center;
padding: 20px;
box-shadow: 0 0 0 2000px red;
}
<div class="wrap"></div>

如果您知道图像的确切尺寸,则可以使用linear-gradient,您可以在其中指定尺寸,以便它们覆盖部分背景。

下面是我使用方形图像的示例:

body {
margin:0;
height:100vh;
background:pink;
}
.image {
height: 100%;
background:  
linear-gradient(#000,#000) left/calc((100vw - 100vh)/2) 100%  no-repeat,
linear-gradient(#000,#000) right/calc((100vw - 100vh)/2) 100%  no-repeat,

url(https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png) center center/auto 100% no-repeat;
}
<div class="image"></div>

另一个具有相同图像的另一个设置的示例:

body {
margin:0;
height:100vh;
background:pink;
}
.image {
height: 100%;
background:  
linear-gradient(#000,#000) top/ 100% calc((100vh - 158px)/2)  no-repeat,
linear-gradient(#000,#000) bottom/ 100% calc((100vh - 158px)/2)  no-repeat,
linear-gradient(#000,#000) left/calc((100vw - 158px)/2) 100%  no-repeat,
linear-gradient(#000,#000) right/calc((100vw - 158px)/2) 100%  no-repeat,

url(https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png) center center no-repeat;
}
<div class="image"></div>

最新更新