显示背景图像的透明边框[重复]

问题描述 投票:0回答:2

我有这个:

Solid border that should be transparent

我想实现这个:

Transparent border showing background image

我有一个大的外部 div(红色背景)和一个较小的内部 div(绿色背景)。小 div 有一个边框,我希望边框显示为透明以显示后面的背景。这可以用 HTML/CSS 实现吗?

css border mask
2个回答
11
投票

您可以使用伪元素实现显示背景图像的透明边框

红色背景是伪元素的边框,透明边框由元素背景和伪元素边框之间的间隙创建:

演示

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>

输出:

你也可以使用 box-shadow 而不是 border 这样你就不必为伪元素的

top/left
定位使用负值。浏览器支持虽然不如边框好

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>


3
投票

你可以用固定的背景图片来伪造它:

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>
© www.soinside.com 2019 - 2024. All rights reserved.