css置中的實現方法

來源:互聯網
上載者:User

1.有這樣一段代碼:

<p>您在<img src="images/querenzhifu.png">後會指引去支付寶,按照支付寶的提示完成付款操作。</p>
這樣在一個區塊層級元素下,實現img的置中,我們不能直接給絕對位置去實現它,因為絕對位置會產生圖片覆蓋文字的效果,那麼這時怎樣進行置中呢,

方法很簡單,不需要對p標籤設定寬高或是其他的什麼,只需給img一個vertical-align:middle,就可以實現圖片與文字的一個置中了。


一.內嵌元素的置中方法,如下:

水平置中:

1.行內元素,直接設定text:align:center

2.Flex布局,設定display:flex; justify-content:center;該方法呢,有些瀏覽器不支援。

垂直置中:

1.父元素高度確定的單行文本或行內元素,設定height = line-height;

2.父元素高度確定的多行文本或行內元素

a:插入table,然後設定vertical-align:middle;

b:先設定display:table-cell,再設定vertical-align:middle;

二.區塊層級元素的置中方法,如下:

水平置中:

1.定寬區塊層級元素,設定margin:0 auto;

2.不定寬區塊層級元素,

a:在元素外加入table標籤(完整的table,包括table,tbody,tr,td),該元素寫在td內,然後設定margin的值為auto;

b:給該元素設定display:inline;

c:給該元素設定position:relative;left:50%;

垂直置中:

1.使用position:absolute(fixed),設定left、top、margin-left、margin-top的屬性;

2.利用display:table-cell屬性;

3.使用css3的新屬性transform:translate(x,y),x和y是相對x軸和y軸移動,可以給負值;

4.使用:before,在元素前插入...;



好了,本篇就到這裡了。

相關文章

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.