Transparent Border showing background image

2019-01-20 13:39发布

问题:

I have this:

I want to achieve this:

I have a big outer div (with red background) and a smaller-inner div (with green background). The small div has a border, I want the border to appear as transparent to show the behind background. Is this achievable with HTML/CSS?

回答1:

You can achieve the transparent border showing background image using a pseudo element.

The red background is the border of the pseudo element and the transparent border is created by the gap between the element's background and the pseudo element's border:

DEMO :

body{
    background:url('https://farm4.staticflickr.com/3771/13199704015_72aa535bd7.jpg');
    background-size:cover;
}
.big{
    margin:50px;
    padding:50px;
    min-height:500px;
    overflow:hidden;
}
.big p{
    position:relative;
    z-index:1;
}
.small{
    position:relative;
    background:teal;
    width:150px;height:150px;
    margin:25px;
    z-index:0;
}
.small:before{
    content:'';
    position:absolute;
    top:-5025px; left:-5025px;
    width:200px; height:200px;
    border:5000px solid rgba(255,255,255,0.8);
    background:none;
}
<div class="big">
    <p>content here</p>
    <div class="small"></div>
    <p>content here</p>
</div>

output:

You can also use box-shadow instead of border so you don't have to use negative values for the top/left positioning of the pseudo element. Browser support isn't as good as border though :

body{
    background:url('https://farm4.staticflickr.com/3771/13199704015_72aa535bd7.jpg');
    background-size:cover;
}
.big{
    margin:50px;
    padding:50px;
    min-height:500px;
    overflow:hidden;
}
.big p{
    position:relative;
    z-index:1;
}
.small{
    position:relative;
    background:teal;
    width:150px;height:150px;
    margin:25px;
    z-index:0;
}
.small:before{
    content:'';
    position:absolute;
    top:-25px; left:-25px;
    width:200px; height:200px;
    box-shadow: 0px 0px 0px 5000px rgba(255,255,255,0.8);
    background:none;
}
<div class="big">
    <p>content here</p>
    <div class="small"></div>
    <p>content here</p>
</div>



回答2:

You can fake it with a fixed background image:

http://codepen.io/pageaffairs/pen/LENMgZ

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>

body {background: url(http://pageaffairs.com/sp/bg.jpg);}
.cont {background: rgba(256,0,0,0.4); width: 400px; height: 400px; margin: 40px; padding: 40px;}
.box {width: 100px; height: 100px; padding: 10px; background: url(http://pageaffairs.com/sp/bg.jpg) fixed;}
.box-inner {width: 100px; height: 100px; background: green;}
</style>
</head>
<body>

<div class="cont">
    <p>This is content inside the big div.</p>
    <div class="box">
        <div class="box-inner"></div>
    </div>
    <p>More content inside the big div.</p>
</div>

</body>
</html>