页面元素居中是很常见的需求,考虑到兼容性,有时候css很难满足
下面介绍一种简单的元素居中方法
用到定位属性
基本语法
position : static | absolute | fixed | relative
语法取值
static : 默认值。无特殊定位,对象遵循HTML定位规则
absolute : 将对象从文档流中拖出,使用 left , right , top , bottom 等属性相对于其最接近的一个最有定位设置的父对象进行绝对定位。 如果不存在这样的父对象,则依据 body 对象。而其层叠通过 z-index 属性定义
fixed : 未支持。对象定位遵从绝对(absolute)方式。但是要遵守一些规范
relative : 对象不可层叠,但将依据 left , right , top , bottom 等属性在正常文档流中偏移位置
使用absolute或者relative都可以实现。但是relative不可折叠
代码如下
若有错误,敬请指出~
absolute : 将对象从文档流中拖出,使用 left , right , top , bottom 等属性相对于其最接近的一个最有定位设置的父对象进行绝对定位。 如果不存在这样的父对象,则依据 body 对象。而其层叠通过 z-index 属性定义
fixed : 未支持。对象定位遵从绝对(absolute)方式。但是要遵守一些规范
relative : 对象不可层叠,但将依据 left , right , top , bottom 等属性在正常文档流中偏移位置
使用absolute或者relative都可以实现。但是relative不可折叠
代码如下
<!DOCTYPE html>
<html>
<head>
<title>center_demo.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<style type="text/css">
.parent{
width:90%;
height:90%;
background-color: blue;
position:absolute;
}
.children{
position:absolute;
left:50%;
top:50%;
text-align: center;
width:200px;
height:100px;
background-color: white;
/*单个元素可以使用line-height填充父容器*/
line-height: 100px;
}
</style>
</head>
<body>
<div class="parent">
<div class="children">
hello word
</div>
</div>
</body>
<script type="text/javascript">
setSizeByClient();
window.οnresize=setSizeByClient;//监听
function setSizeByClient(){
//获取父容器高宽的1/2,然后减去元素本身的高宽的1/2,
//($(this).parent().width()-$(this).width())/2
//($(this).parent().height()-$(this).height())/2
$(".children").css({"left":$(".parent").width()/2-100+"px","top":$(".parent").height()/2-50+"px"});
};
</script>
</html>
浏览器效果,不论分辨率怎么变化,元素都是居中的
若有错误,敬请指出~