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

时间:2018-06-04 14:33:49

标签: css background background-image

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

问题是我需要图像的所有空间 为黑色。如果我用[].some(...)设置它 - 图像的透明像素也会变黑,这是错误的。

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

我目前的代码:

background: black url(...

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

2 个答案:

答案 0 :(得分:2)

我建议使用巨大的盒子阴影;



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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果您知道图片的确切尺寸,可以使用linear-gradient来指定尺寸,以便部分覆盖背景。

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

&#13;
&#13;
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;
}
&#13;
<div class="image"></div>
&#13;
&#13;
&#13;

使用同一图像的另一个设置的另一个示例:

&#13;
&#13;
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;
}
&#13;
<div class="image"></div>
&#13;
&#13;
&#13;

相关问题