CSS讓一個元素水平垂直置中

來源:互聯網
上載者:User

標籤: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讓一個元素水平垂直置中

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.