我需要使用HTML/CSS创建一个覆盖元素,该元素仅覆盖某个容器,而不是整个页面。我可以使用 position:absolute;
,然后到处都有0px,但是问题是我无法定位应覆盖的容器,它必须保持静态位置,然后position:absolute;
与此容器无关。
所以我试图将此设置高度和宽度固定到100%:
body {
background-color: grey;
}
#ovl {
height: 100%;
width: 100%;
background-color: #a10000a1;
}
#container {
border: 4px dotted blue;
}
<!DOCTYPE html>
<html>
<body>
<div id="container">
<div id="ovl">
This Overlay should hide the images.
</div>
<img height=300 src="1.png" class="imgs" alt="Error!">
<img height=300 src="2.png" class="imgs" alt="Error!">
<img height=300 src="3.png" class="imgs" alt="Error!">
</div>
</body>
</html>
我希望红色的叠加元素将覆盖整个容器和其中的三个图像,但我明白了。红色覆盖层不涵盖三个图像(音乐得分(。我的代码中有错误吗?如何修复?
CSS网格可以做到这一点。无需定位。
body {
background-color: grey;
}
#ovl {
background-color: #a10000a1;
grid-column: 1 / -1;
grid-row: 1;
z-index: 2;
color: white;
}
#container {
border: 4px dotted blue;
display: inline-grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto;
}
img {
grid-row: 1;
max-height: 100%;
width: auto;
}
img:nth-of-type(1) {
grid-column: 1;
}
img:nth-of-type(2) {
grid-column: 2;
}
img:nth-of-type(3) {
grid-column: 3;
}
<div id="container">
<div id="ovl">
This Overlay should hide the images.
</div>
<img height=300 src="http://www.fillmurray.com/g/140/100" class="imgs" alt="Error!">
<img height=300 src="http://www.fillmurray.com/g/140/100" class="imgs" alt="Error!">
<img height=300 src="http://www.fillmurray.com/g/140/100" class="imgs" alt="Error!">
</div>
这是使用CSS网格的解决方案:
.grid{
display:grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
/* grid-template-row: 1fr; */
border: 3px dotted blue;
width: 100%;
}
.overlay{
background: #000000a1;
color: white;
grid-column: 1 / span 3;
grid-row: 1/ span 3;
z-index: 1;
}
.img1{
grid-column: 1 / span 2;
grid-row: 1/ span 1;
}
.img2{
grid-column: 1 / span 2;
grid-row: 2/ span 2;
}
.img3{
grid-column: 1 / span 2;
grid-row: 3/ span 3;
}
<div class="grid">
<div class="overlay">
This Overlay should hide the images.
</div>
<img src="1.png" class="img1" alt="Error!">
<img src="2.png" class="img2" alt="Error!">
<img src="3.png" class="img3" alt="Error!">
</div>
如果您想尝试实验
进行覆盖的最佳方法是在孩子中使用 position:absolute
,而父母则使用position:relative
,这将是您的CSS代码
body {
background-color: grey;
}
#ovl {
background-color: #a10000a1;
position: absolute;
width: 100%;
height: 100%;
}
#container {
border: 4px dotted blue;
position: relative;
}
请参阅此处的结果
所有其他没有位置的解决方案绝对/相对可能非常麻烦
在我对问题的理解时,您的divs出现了错误。改用此方法:
<!DOCTYPE html>
<html>
<body>
<div id="ovl">
<div id="container">
This Overlay should hide the images.
</div>
<img height=300 src="1.png" class="imgs" alt="Error!">
<img height=300 src="2.png" class="imgs" alt="Error!">
<img height=300 src="3.png" class="imgs" alt="Error!">
</div>
</body>
</html>
CSS
body {
background-color: grey;
}
#ovl {
height: 100%;
width: 100%;
background-color: #a10000a1;
}
#container {
border: 4px dotted blue;
}