需要准备的材料分别有:电脑、浏览器、html编辑器。
1、首先,打开html编辑器,新建html文件,例如:index.html,编写问题基础代码。
2、在index.html中的<body>标签中,输入html代码:
reset()
window.onresize = function () {
reset()
}
function reset() {
var left = (window.innerWidth - $('div').width())/2
var top = (window.innerHeight - $('div').height())/2
$('div').css('margin-left', left + 'px')
$('div').css('margin-top', top + 'px')
}
3、浏览器运行index.html页面,此时无论怎么拉伸窗口,div都会自动调整到屏幕正中央。
html中使一个table或者div永远处于中间位置,首先需要理解块元素的概念,如div、table都是width和height属性,然后在通过css中的一个margin属性,来实现居中,具体用法看下图: 不管浏览器的宽度是多少,这个属性就会将div居中,具体看下代码: #...<div class="mask-box"></div>
<div class="dialog-box">
弹窗内容
</div>
通过fixed定位实现, ".mask-box" 模拟背景,".dialog-box"作为弹窗容器,里面写弹窗的内容。
通过控制样式,切换 display:block display: none实现点击出现、点击关闭弹窗。
.mask-box{
/* 切换 display:block display: none*/
position: fixed
left: 0
right: 0
top: 0
bottom: 0
background:rgba(0,0,0,0.7)
z-index: 98
}
.dialog-box{
/* 切换 display:block display: none*/
position: fixed
left: 50%
top: 50%
transform: translate(-50%,-50%)
width: 300px
height: 200px
background: #fff
/* 按实际情况 设置z-index */
z-index: 98
}