CSS控制元素對齊的技巧

來源:互聯網
上載者:User
父元素一定是塊元素,根據子項目不同分為以下幾種:

1.子項目是行內元素:如:a,span

a.水平置中:在父元素上設定: text-align:center;

b.垂直置中:在行內子項目上設定行高與父元素相同: line-height

.box1 {width: 200px;height: 200px;background-color: #FFFF0A;text-align: center;  /*可以使內部行內元素水平置中*/}.box1 a {line-height: 200px;  /*子項目設定行高與父元素高度相同*/}<div class="box1">     <a href="">topic.alibabacloud.com</a></div>

2. 子項目是多行內聯文本

a.水平置中:父元素設定text-align:center

b.垂直置中:父元素設定:display:table-cell;vertical-align:middle

.box2 {width: 200px;height: 200px;background-color: #FC0107;text-align: center;  /*可以使內部多行行內元素水平置中*//*以下二個聲明可以使多行文本垂直置中*/display: table-cell;  /*設定顯示方式為表格儲存格*/vertical-align: middle; /*設定該儲存格內的元素垂直置中*/}<div class="box2"><span>php中文網</span><br><span>www.php.cn</span></div>

3. 子項目是塊元素:

a.水平置中:子項目設定左右自動: margin: auto;

b.垂直置中:與多行內聯文本處理方式一致:display:table-cell;vertical-align:middle

.box3 {width: 200px;height: 200px;background-color: #66CCFF;/*以下二個聲明可以使塊級子項目垂直置中*/display: table-cell;  /*設定顯示方式為表格儲存格*/vertical-align: middle; /*設定該儲存格內的元素垂直置中*/}.box3 .child {width: 100px;height: 100px;background-color: #F4FF0A;margin: auto;  /*水平置中*/}<div class="box3"><div class="child"></div></div>

4. 子項目是不定寬的塊元素:最常見的分頁導航

a.水平置中:子項目轉行內元素,父元素加:text-align:center

b.垂直置中:可給分頁的ul加行高line-height=parent.height

c.底邊置中:更為常用,與多行內聯文本垂直處理方式一致,vertical-align:bottom;

.box4 {width: 200px;height: 200px;background-color: #FD6FCF;text-align: center;  /*可以使行內元素水平置中*//*以下二個聲明可以使塊級子項目垂直置中*/display: table-cell;  /*設定顯示方式為表格儲存格*/vertical-align:bottom; /*設定該儲存格內的元素底邊置中*/}.box4 ul {margin: 0;padding: 0;/*line-height: 200px;*/}.box4 li {list-style: none;display: inline;}<div class="box4"><ul><li><a href="">1</a></li><li><a href="">2</a></li><li><a href="">3</a></li><li><a href="">4</a></li><li><a href="">5</a></li></ul></div>
相關文章

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.