css和HTML布局小技巧

來源:互聯網
上載者:User

標籤:title   char   lang   絕對位置   absolute   技巧   utf-8   child   屬性   

一:水平置中

      1. 如下所示,讓child在parent中水平置中

<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title>    <style>        .parent{ width:300px; height:200px; border:1px solid #000; text-align: center; }        .child{  width: 50px;  height:50px;  border:1px solid red;  display: inline-block;}    </style></head><body><div class="parent">    <div class="child"></div></div></body></html>

第一種方法:給父元素添加text-align:center屬性,把子項目變成行內框,display:inline-block;(子項目可以是行內元素也可以是區塊層級元素)

第二種方法:給子項目添加margin:0 auto;屬性(子項目必須有寬度,而且必須是區塊層級元素);

 

第三種方法:利用絕對位置和相對定位實現

 

       .parent{            width:300px;            height:200px;            border:1px solid #000;            position: relative;//設定相對定位以配合子項目的絕對位置        }        .child{            width: 50px;            height:50px;            border:1px solid red;            position: absolute;            left:50%;            margin-left: -25px;//元素寬度的一半        }

 

二,垂直置中

第一種方法:和上面一樣利用絕對位置

       .parent{            width:300px;            height:200px;            border:1px solid #000;            position: relative;//設定相對定位以配合子項目的絕對位置        }        .child{            width: 50px;            height:50px;            border:1px solid red;            position: absolute;            top:50%;            margin-top: -25px;        } 

第二種方法:

給parent增加
display:table-cell;
vertical-align: middle;

 

css和HTML布局小技巧

相關文章

聯繫我們

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