關於css浮動元素的置中

來源:互聯網
上載者:User

本文我們主要和大家介紹關於css浮動元素的置中,置中對於大家來說指的是頁面了,此時我們通常使用提50%來實現了,下面來看一個css浮動元素的置中的例子,希望能協助找到大家。

<script>ec(2);</script>


關於浮動元素的置中,其實不太常用,但為了應付某些奇葩的面試官,也要知道怎麼解決這個問題。

貼出一段css代碼:

width:50%; height:300px; float:left; margin-left:50%;  position:relative; left:-25%;background-color:#ccc;

要害在於,給一個左邊距,然後定位,讓left值為p寬度的一半,即可實現。

其實這種方法也是做彈窗,讓它位於瀏覽器中間位置常用的方法:給個左(上)邊距,在position個left(top)值。

例子

 <style type="text/css">  .ps{background:#ccc;width:600px;height:300px;margin:50px auto 0;}  .ps p{margin:0 auto;background:#000;width:400px;text-align:center;}  p{float:left;height:100px;width:98px;background:#fff;border:1px solid red;margin:0 auto;}    </style>   <body>  <p class="ps">  <p>  <p>p1</p>  <p>p2</p>  <p>p3</p>  <p>p4</p>  </p>  </p>   </body>

我們發現也能夠實現置中效果,但是其可擴充性較差,如果刪除一個p或者添加一個p,則需要對.ps p這個樣式裡的width進行修改。

相關文章

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.