水平垂直居中

2022-05-01 09:51:06 字數 2461 閱讀 5388

1.利用絕對定位

doctype html

>

<

html

>

<

head

>

<

meta

charset

="utf-8"

/>

<

title

>水平垂直居中

title

>

<

style

>

.center

style

>

head

>

<

body

>

<

div

class

="center"

>垂直水平居中

div>

body

>

html

>

top與left設為50%,margin-left為寬度一半的負值,margin-top為高度一半的負值

此方法最常見,但僅僅適用於已知寬高的情況下。

2.絕對定位結合transform

doctype html

>

<

html

>

<

head

>

<

meta

charset

="utf-8"

/>

<

title

>水平垂直居中

title

>

<

style

>

.center

style

>

head

>

<

body

>

<

div

class

="center"

>垂直水平居中

div>

body

>

html

>

可在未知寬高時使用,但在ie8及以前的瀏覽器內不支援,且內部文字可能因為移動而稍顯模糊,這是因為transform物件的寬高不是偶數,50%位移後產生了小數。

3.利用flex

doctype html

>

<

html

>

<

head

>

<

meta

charset

="utf-8"

/>

<

title

>水平垂直居中

title

>

<

style

>

.cont-center

.center

style

>

head

>

<

body

>

<

div

class

="cont-center"

>

<

div

class

="center"

>垂直水平居中

div>

div>

body

>

html

>

ie11以下不支援justify-content、align-items等屬性

4.利用ifc布局,即空的img或者偽元素

doctype html

>

<

html

>

<

head

>

<

meta

charset

="utf-8"

/>

<

title

>水平垂直居中

title

>

<

style

>

.cont-center

.center

.cont-center:after

style

>

head

>

<

body

>

<

div

class

="cont-center"

>

<

div

class

="center"

>垂直水平居中

div>

div>

body

>

html

>

5.利用calc

根據雅虎的35個前端優化法則,並不提倡使用calc,略過。

css 水平居中 垂直居中 水平垂直居中

一 水平居中 1 行內元素水平居中text align center 2 塊級元素水平居中margin 0 auto 3 多個塊狀元素的水平居中 實現多個水平排列的塊狀元素的水平居中,是將要水平排列的塊狀元素設為display inline block,然後在父級元素上設定text align ce...

css水平居中 垂直居中 水平垂直居中

css水平居中 垂直居中 水平垂直居中 水平居中 行內元素 block text align 塊級元素 方案一 分寬度定不定兩種情況 定寬度 margin 0 auto 作用 使盒子自己居中,意思是上下距離為0,auto就是左右自適應兩邊距離 不定寬度 設定子元素display inline blo...

居中 水平 垂直 水平垂直

將子元素的display設定為inline block,使子元素變成行內元素 這種方法的不足之處在於,子元素的text align繼承了父元素的center,文字也居中顯示,所以需要在子元素中設定text align left 思路二 在本身元素設定margin 0 auto實現塊級元素水平居中 若...