dom居中


页面元素居中是很常见的需求,考虑到兼容性,有时候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不可折叠
代码如下
<!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>
浏览器效果,不论分辨率怎么变化,元素都是居中的


若有错误,敬请指出~


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值