Reputation: 2812
I have a fixed size image and part of it is transparent, which I currently use as a DIV background. I must place the image precisely in the screen center.
The problem is that I need the all space around the image to be black. If I set it with background: black url(...
- image's transparent pixels also become black, which is wrong.
Another problem is that the website content is dynamic, so I can't cheat with 2 DIVs with the same background image and different filters. I need to look through transparent pixels clearly.
My current code:
<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>
In short - I need to look at the content through the transparent part of the image, the other part of the screen must be black. How do I achieve this?
Upvotes: 0
Views: 1048
Reputation: 115011
I'd suggest an enormous box-shadow;
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>
Upvotes: 2
Reputation: 272779
If you know the exact dimension of your image you can use linear-gradient
where you can speficy a size so they cover partially the background.
Here is an example where I used a square image:
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>
Another example with another setting of the same image:
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>
Upvotes: 1