913815ccmm

 

### 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>

 

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

分类:

技术点:

相关文章: