1.块在父容器里居中常用方法——
position: absolute;
left: 50%;
top: 50%;
margin-left: -250px;
margin-top: -200px;
width: 500px;
height: 400px;
其中:
margin-left: -250px; /* 元素本身文档宽度的一半*/
margin-top: -200px /* 元素本身文档高度的一半*/
/* 注意-有滚动条时:这种居中必须滚动条滑到中间,效果不好 */
2 块在window窗口居中
<body>
<div class="con">
<form class="show">
用户名: <input type="text" name="name" id=""/>
</form>
</div>
</body>
<script src="jquery-3.0.0.js"></script>
<script>
$( function(){
//初始化
$("form").css("top", $(window).height()/2+"px");
$("form").css("left", $(window).width()/2+ "px");
$("form").css("margin-top",-200+ "px");
$("form").css("margin-left",-250+"px")
//滚动事件 窗口大小变化事件
$(window).on("resize scroll", function () {
$("form").css("top", $(window).height()/2+"px");
$("form").css("left", $(window).width()/2+ "px");
$("form").css("margin-top",-200+ document.body.scrollTop+"px");
$("form").css("margin-left",-250+ document.body.scrollLeft+"px")
})
});
</script>
body{
width: 2000px;
height: 2800px;
}
.con form{
/* 在指定父容器 里面居中*/
/* left: 50%;
top: 50%;
margin-left: -250px;
margin-top: -200px;*/
position: absolute;
width: 500px;
height: 400px;
background: rgba(255,0,0,0.5);
}