首页 > Web开发 > 详细

让HTML页面元素居中的各种实现方法

时间:2015-10-02 21:07:27      阅读:228      评论:0      收藏:0      [点我收藏+]

 

### CSS实现方法

<style type="text/css">
  #center{
	width:300px;
	height:200px;
	background:red;
	position:absolute;
	top:50%;
	left:50%;
	margin-left:-150px;
	margin-top:-100px;
  }
</style>
<div id="center"></div>

### JavaScript实现方法

 1 <body>
 2   <div id="center"></div>
 3   <script>    
 4     function toCenter(id){
 5       var w = 300;
 6       var h = 200;
 7       document.getElementById(id).style.cssText = "background:red;width:"+ w +"px;height:"+ h +"px;position:absolute;top:50%;left:50%;
 8       margin-left:-"+ w/2 +"px;margin-top:-"+ h/2 +"px;"; (注意处理换行问题)
 9     }
10     toCenter("center")
11   </script>
12 </body>

 

### Jquery实现方法

 1 <body>
 2     <div id="center"></div>
 3     <script>            
 4         $("#center").css({
 5             ‘width‘        :‘300px‘,
 6             ‘height‘    :‘200px‘,
 7             ‘background‘:‘red‘,
 8             ‘position‘    :‘absolute‘,
 9             ‘top‘        :‘50%‘,
10             ‘left‘        :‘50%‘,
11             ‘margin-left‘:‘-150px‘,
12             ‘margin-top‘:‘-100px‘
13         });
14     </script>
15 </body>

 

### 后续还会再添加一些居中的方法,便于思路放的更宽。

让HTML页面元素居中的各种实现方法

原文:http://www.cnblogs.com/913815ccmm/p/4852671.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!