CSS絕對位置元素置中的幾種方法

來源:互聯網
上載者:User

標籤:pre   translate   for   lin   body   sla   .net   auto   max   

CSS置中絕對位置元素的方法,有很多種,下面是我收集的幾種

1,div寬度未知1

<body>  <div style="position: absolute; left: 50%;">    <div style="position: relative; left: -50%; border: dotted red 1px;">      沒有寬度<br />      照樣置中,嘿嘿嘿    </div>  </div></body>

demo:https://jsfiddle.net/skura23/0123wmsg/

 

2,div寬度未知2

<div class="outer">    <div class="inner">置中<br/>蓄力中</div></div>.outer {    position: relative; /* or absolute */        /* unnecessary styling properties */    margin: 5%;    width: 80%;    height: 500px;    border: 1px solid red;}.inner {    position: absolute;    left: 50%;    top: 50%;    transform: translate(-50%, -50%);        /* unnecessary styling properties */    max-width: 50%;    text-align: center;    border: 1px solid blue;}

demo: http://jsfiddle.net/skura23/6xo11zwv/210/

ps:此方法適合ie8以上的瀏覽器

 

3,div寬度已知

<body>  <div>    <div id="content">      置中蓄力中    </div>  </div></body>#content {  position: absolute;   left: 0;   right: 0;   margin-left: auto;   margin-right: auto;   width: 100px; /* 要設定寬度 */}

demo:https://jsfiddle.net/skura23/rk3qfvv2/1/

 

--------------------------------------------------

後面有其他的方法的話,會繼續添加

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.