网上有许多令一个div上下左右垂直居中的方式,都是大同小异,我最喜欢的是还position+transform样式来实现,下面是代码实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>center</title>
</head>
<style>
body {
margin: 0;
padding: 0;
}
#fix-mid {
width: 200px;
height: 200px;
background: red;
position: absolute;
top: 50%;
left: 50%;
opacity: 1;
z-index: 110;
transform: translate(-50%,-50%) scale(1, 1);
animation: g-zoomEnter .2s cubic-bezier(0.18, 0.89, 0.32, 1.28);
}
.fix-bg {
position: fixed;
background: rgba(0, 0, 0, 0.4);
z-index: 10;
top: 0;
bottom: 0;
left: 0;
right: 0;
animation: g-fadeEnter .4s ease;
}
.none {
display: none;
}
/* 背景渐变 */
@keyframes g-fadeEnter {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
/* 定宽居中且有小变大 */
@keyframes g-zoomEnter {
0% {
opacity: 0;
transform: translate(-50%,-50%) scale(0, 0);
}
100% {
opacity: 1;
transform: translate(-50%,-50%) scale(1, 1);
}
}
</style>
<body>
<button id="btn">点击弹出居中div</button>
<div class="fix-bg none">
<div id="fix-mid" onclick=" event.stopPropagation()">
1
</div>
</div>
</body>
<script>
var btn = document.getElementById(‘btn‘);
var fixedObj = document.getElementsByClassName(‘fix-bg‘)[0];
var oDiv = document.createElement("div");
btn.onclick = function() {
fixedObj.classList.remove(‘none‘);
}
fixedObj.onclick = function(e) {
fixedObj.classList.add(‘none‘);
}
</script>
</html>