利用css來讓一個div在頁面中垂直置中的方法

來源:互聯網
上載者:User

標籤:enter   justify   cal   頁面   bsp   彈性布局   ems   window   左移   

 

一、如何讓一個div在頁面中垂直置中(請至少列出三種)

 

1.距離頁面視窗左邊框和上邊框的距離設定為50%,這個50%就是指頁面視窗的寬度和高度的50%,最後將該DIV分別左移和上移,左移和上移的大小就是該DIV寬度和高度的一半。

width:300px; 

 height:200px; 

 position:absolute;

 left:50%

 top:50%;  

 margin:-100px 0 0 -150px ;

2.使用jquery代碼

 $(window).resize(function(){ 

   $(".mydiv").css({ 

     position: "absolute", 

     left: ($(window).width() - $(".div").outerWidth())/2, 

     top: ($(window).height() - $(".div").outerHeight())/2 

   });        

}); 

3.使用絕對位置;top,bottom,left,right分別都為零

父元素設定為:

  width:800px;

           height:500px;

           border:2px solid #000;

           position:relative;

子項目設定為:

  width:200px;

            height:200px;

            margin: auto;

            position: absolute;

            top: 0; left: 0; bottom: 0; right: 0;

            

 

4.(此方法暫時只能設定元素在父級元素中垂直置中,還沒有實現水平置中),使用display:table-cell

父元素設定為:

width:800px;

height:500px;

border:2px solid #000;

display:table-cell;

vertical-align:middle;

text-align: center;

子項目設定為:

 

width:200px;

height:200px;

 

display:inline-block;

5.實用彈性布局的方式來解決

父級元素設定為

width:800px;

height:500px;

border:2px solid #000;

display:flex;

justify-content:center;

align-items:center;

 

子項目設定為:

width: 200px;

height: 200px;

background-color: red;

利用css來讓一個div在頁面中垂直置中的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.