不改變DOM,給元素增加遮罩(背景)

如題,現需要給modal元素增加一個全局遮罩或全局背景,要求不能修改DOM結構和修改JS代碼:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>CSS</title>
<style>
		.modal {
			position: fixed;
			display: flex;
			align-items: center;
			justify-content: center;
			top: 50%;
			left: 50%;
			color:#fff;
			transform: translate(-50%,-50%);
			width: 320px;
			height: 240px;
			z-index: 1;
			background: red;
		}
</style>
</head>
<body>
 <div>某些元素</div>
  <div class="modal">已存在的元素</div>
</body>
</html>

在這裏插入圖片描述
可以考慮通過:before僞元素增加全局背景:

<!DOCTYPE html>
<html>
<head>
	<meta charset=utf-8 />
	<title>CSS</title>
	<style>
		.modal {
			position: fixed;
			display: flex;
			align-items: center;
			justify-content: center;
			top:20%;
			left: 0;
			right: 0;
			margin: 0 auto;
			width: 320px;
			height: 240px;
			z-index: 1;
			background: red;
		}
		.modal:before{
			content:"";
			position: fixed;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			width: 100%;
			height: 100%;
			z-index:-1;
			background: rgba(0,0,0,.5);
		}
	</style>
</head>
<body>
<div>某些元素</div>
<div class="modal">已存在的元素</div>
</body>
</html>

此時自身元素也被擋住了,顯然不符合需求:
在這裏插入圖片描述
四處碰壁以及參考層疊上下文後得:

<!DOCTYPE html>
<html>
<head>
	<meta charset=utf-8 />
	<title>CSS</title>
	<style>
		.modal {
			position: fixed;
			display: flex;
			align-items: center;
			justify-content: center;
			top:20%;
			left: 0;
			right: 0;
			margin: 0 auto;
			width: 320px;
			height: 240px;
			z-index: 1;
			background: red;
		}
		.modal:before{
			content:"";
			position: fixed;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			width: 100%;
			height: 100%;
			z-index:-2;
			background: rgba(0,0,0,.5);
		}
		.modal:after{
			content: '';
			position: absolute;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			z-index: -1;
			background: red;
		}
	</style>
</head>
<body>
<div>某些元素</div>
<div class="modal">已存在的元素</div>
</body>
</html>

最終呈現效果:
在這裏插入圖片描述
參考:http://www.w3.org/TR/CSS21/visuren.html#stack-level

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章