垂直水平居中的四種方式

2021-08-30 11:23:28 字數 908 閱讀 9362

方案1:position 元素已知寬度

父元素設定為:position: relative; 

子元素設定為:position: absolute; 

距上50%,據左50%,然後減去元素自身寬度的距離就可以實現 

效果圖:

方案2:position transform 元素未知寬度如果元素未知寬度,只需將上面例子中的margin: -50px 0 0 -50px;替換為:transform: translate(-50%,-50%);**:

.box 

.content

方案3:flex布局**:

.box 

.content

方案4:table-cell布局因為table-cell相當與**的td,td為行內元素,無法設定寬和高,所以巢狀一層,巢狀一層必須設定display: inline-block;td的背景覆蓋了橘黃色,不推薦使用

效果圖:

元素水平垂直居中的四種方式

1.flex彈性盒 使用flex彈性盒的居中方式,我們只需要給與其父元素設定 這三個屬性就可以讓其內部元素水平垂直居中 父元素內只有乙個子元素 2.position定位 要求父元素是定位屬性元素也就是position不為static 2.1margin負值 給要水平垂直的元素設定屬性 2.2marg...

html,將元素水平,垂直居中的四種方式

將元素垂直,水平居中分兩種情況 乙個是元素尺寸固定,二是元素尺寸不固定 一.尺寸固定 方法1 定位 50 margin負距 方法2 四方為都為0 margin auto 3 方法三,元素尺寸不固定 4.方法四 使用偽元素 利用inline block與vertical align配合偽元素達到垂直居...

水平垂直居中的四種方法

lang en charset utf 8 水平垂直居中title color center container1 container1 center container2 container2 center container3 container3 center container4 style...