我有这个:
我想实现这个目标:
我有一个大的外部div(红色背景)和一个较小的内部div(绿色背景)。小div有一个边框,我希望边框显示为透明以显示背后的背景。这是用HTML / CSS实现的吗?
答案 0 :(得分:10)
您可以使用伪元素实现透明边框显示背景图像。
红色背景是伪元素的边框,透明边框由元素背景和伪元素边框之间的间隙创建:
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>
输出:
您也可以使用box-shadow而不是border,这样就不必为伪元素的top/left
定位使用负值。浏览器支持isn't as good作为边界:
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>
答案 1 :(得分: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>