如何css屬性實現各種置中填充方式代碼詳解

來源:互聯網
上載者:User
首先是 水平置中,最簡單的辦法當然就是

margin:0 auto;

也就是將margin-left和margin-right屬性設定為auto,從而達到水平置中的效果。

那麼其他的辦法呢?

line-height

首先介紹文字的水平置中方法:

<p class="wrap">劉放</p>

利用line-height設為height的一樣即可:

.wrap{  line-height: 200px;/*垂直置中關鍵*/  text-align:center;   height: 200px;  font-size: 36px;  background-color: #ccc;}

效果如下:

padding填充

利用padding和background-clip配合實現p的水平垂直置中:

<p class="parent">  <p class="children"></p></p>

通過backgroun-clip設定為content-box,將背景裁剪到內容區外沿,再利用padding設為外p減去內p的差的一半,來實現:

.parent{ margin:0 auto; width:200px; height:200px; background-color:red;}.children { width: 100px; height: 100px; padding: 50px; background-color: black; background-clip:content-box;/*置中的關鍵*/

效果如下:

margin填充

接下來介紹margin填充的方式來實現水平垂直置中。
首先我們還是定義父子p:

<p class="parent">  <p class="children"></p></p>

這裡我們利用將子p的margin-top設定為父p高度減去子p高度的一半,然後再通過overflow設定為hidden來觸發父p的BFC,LESS代碼如下:

@parentWidth:200px;@childrenWidth:50px;.parent { margin:0 auto; height:@parentWidth; width:@parentWidth; background: red; overflow:hidden;/*觸發BFC*/}.children { height:@childrenWidth; width:@childrenWidth; margin-left:auto; margin-right:auto; margin-top: (@parentWidth - @childrenWidth) / 2; background:black;}

最後得到置中效果如下:

absolute定位

利用position:absolute搭配top,left 50%,再將margin設為負值也可以對p進行水平垂直置中,首先還是需要定義父子p:

<p class="parent">  <p class="children"></p></p>

然後設定相應的css:

.parent { position:relative; margin:0 auto; width:200px; height:200px; background-color:red;}.children { position:absolute;  left:50%;  top:50%;  margin:-25px 0 0 -25px ; height:50px; width:50px; background-color: black;}

其中的margin中的值為該p寬度的一半,最後:

text-align置中

眾所周知,text-align可以使得一個p中的內容水平置中。但是如果是要將該p中的子p置中呢?可以將子p的display設為inline-block。

.parent { text-align:center; margin:0 auto; width:200px; height:200px; background:red;}.children { positiona;absolute; margin-top:75px; width:50px; height:50px; background: black; display:inline-block;/*使其父元素text-align生效*/}

flex置中

最後來介紹一下CSS3中的display:flex來實現的水平垂直置中的方法。

<p class="parent">  <p class="children">我是通過flex的水平垂直置中噢!</p></p>
html,body{ width: 100%; height: 200px;}.parent { display:flex; align-items: center;/*垂直置中*/ justify-content: center;/*水平置中*/ width:100%; height:100%; background-color:red;}.children { background-color:blue;}

效果如下:

相關文章

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.