標籤:css 垂直置中 水平置中
第一種方法:用margin+絕對位置的方式
相容性:IE6,IE7下完全失效
HTML代碼:
<div id="container"><div class="center"></div> </div>
CSS代碼:
#container{ /*基本樣式*/ width:500px; height:500px; background:#fee; /*定位方式*/ position:relative;} .center{ /*基本樣式*/ width:200px; height:200px; background:#aa0; /*水平置中*/ margin:auto; /*垂直置中*/ position:absolute; top:0; bottom:0; left:0; right:0;}
效果:
650) this.width=650;" src="http://s4.51cto.com/wyfs02/M01/87/D1/wKiom1fiIN_h8pWmAAAII0oSz7M592.png" title="QQ20160921135521.png" alt="wKiom1fiIN_h8pWmAAAII0oSz7M592.png" />
第二種方法:用inline-block和table-cell
相容性:IE6,IE7下垂直置中失效
CSS代碼:
#container{ /*基本樣式*/ width:500px; height:500px; background:#fee; /*display*/ display:table-cell; text-align:center; vertical-align:middle;} .center{ /*基本樣式*/ width:200px; height:200px; background:#aa0; /*display:通過轉為行內塊配合父級元素使用text-align實現水平置中*/ display:inline-block;}
第三種方法:用純position
相容性:所有瀏覽器都支援,包括老IE。缺陷:必須明確寬高的固定值
CSS代碼:
#container{ /*基本樣式*/ width:500px; height:500px; background:#fee; /*定位方式*/ position:relative;} .center{ /*基本樣式*/ width:200px; height:200px; background:#aa0; /*定位方式*/ position:absolute; top:150px; /*(父元素的寬高-子項目的寬高)/2*/ left:150px;}
第四種方法:用position和transform
相容性:一看到CSS3屬性就知道了IE8及以下瀏覽器都不支援,個人認為這種方法有些雞肋
CSS代碼:
#container{ /*基本樣式*/ width:500px; height:500px; background:#fee; /*定位方式*/ position:relative;} .center{ /*基本樣式*/ width:200px; height:200px; background:#aa0; /*定位方式*/ position:absolute; top:50%; left:50%; transform:translate(-50%, -50%); -webkit-transform:translate(-50%, -50%);}
第五種方法:用display:flex和margin
相容性:IE9及以下版本垂直置中都失效,由於代碼簡單,推薦移動端使用
CSS代碼:
#container{ /*基本樣式*/ width:500px; height:500px; background:#fee; /*display*/ display:flex;} .center{ /*基本樣式*/ width:200px; height:200px; background:#aa0; /*置中*/ margin:auto;}
第六種方法:用display:flex;和align-items:center;和justify-content:center;
相容性:IE9及以下版本水平垂直置中完全失效,推薦移動端使用
CSS代碼:
#container{ /*基本樣式*/ width:500px; height:500px; background:#fee; /*display*/ display:flex; align-items:center; justify-content:center;} .center{ /*基本樣式*/ width:200px; height:200px; background:#aa0;}
可下載掘金App,搜尋更多更全的方法
本文出自 “dapengtalk” 部落格,請務必保留此出處http://dapengtalk.blog.51cto.com/11549574/1854929
CSS讓一個元素水平垂直置中