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

CSS - background color around image with some transparent pixels

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

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

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

我当前的代码:

<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>

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

如果您知道图像的确切尺寸,您可以使用 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/Whosebug/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/Whosebug/company/img/logos/so/so-icon.png) center center no-repeat;
}
<div class="image"></div>

我建议使用 巨大的 框阴影;

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>