css样式中div永久居中

来源:互联网 发布:c语言以后会被淘汰吗 编辑:程序博客网 时间:2024/05/17 08:58

在网上看了很多, 让div居中,有设置 float:center,text-align:center的方式,但都不够完美。

当然,我这个方法,也是在网上搜到的,只是详细说明一下每一个css属性的含义而已。

  1. <span style="font-size:18px;">.divCenter  
  2. {  
  3.     position:absolute;  
  4.     width:300px;  
  5.     height:160px;  
  6.     left:50%;  
  7.     top:50%;  
  8.     margin-left:-150px;  
  9.     margin-top:-80px;  
  10.     background-color:Green;  
  11. }</span>  

position,既设置绝对定位,以免影响其他控件;

width,height:这个不用说了;

left, top: 50%,这说明什么呢?这说明当我们计算左边距和上边距时,是从body的,中间开始算的。left:50%,说明,以当前屏幕垂直中线为标准;top:50%,说明以当前屏幕的水平中线为标准;

margin-left: 左边距,为负值,说明是以left,既上面提到 的垂直中线为标准,向左边开始计值.;若为正,则是向右开始计值;这里的值应该设置成width的一半,width为300px,则它应该为-150px,这样看上去才会100%距中!

margin-top:道理同margin-left

原创粉丝点击