元素居中浏览器的多种方法集锦

第一种最常见:(元素是绝对定位而不是相对定位)

.inner{ width: 400px; height: 200px; position:absolute; left:50%; top:50%; margin:-100px 0 0 -200px; background-color: green;}

测试表明,这是唯一在IE6-IE7上也表现良好的方法。

优点:

1.      良好的跨浏览器特性,兼容IE6-IE7。

2.      代码量少。

缺点:

1.      不能自适应。不支持百分比尺寸和min-/max-属性设置。

2.      内容可能溢出容器。

3.      边距大小与padding,和是否定义box-sizing: border-box有关,计算需要根据不同情况。

 

第二种:缺点IE7及以下浏览器不兼容

.wrapper{ width: 1000px; height: 600px; margin: auto;  position: absolute;  top: 0; left: 0; bottom: 0; right: 0; background-color: red;}

 

第三种:CSS3变形 transform  IE8不支持

.transformed {   
        width: 500px; height: 400px; background-color: red; margin: auto; position: absolute; top: 50%; left: 50%;  
        -webkit-transform: translate(-50%,-50%);  
        -ms-transform: translate(-50%,-50%);  
        transform: translate(-50%,-50%);  
} 

 

第四种:文字居中 

.wrapper{ background-color: red; width: 1000px; height: 1000px; display: table;}  
.inner{  
  display: table-cell;
  vertical-align: middle;
}  

 

原文链接:http://blog.csdn.net/freshlover/article/details/11579669

posted @ 2015-05-26 16:25  丑萌嘞  阅读(285)  评论(0编辑  收藏  举报