css幾種居中的方法

2021-08-10 16:47:04 字數 1353 閱讀 3162

1、內容居中

style="text-align:center"

align="center"

2、元素居中(只適合塊級元素)

先設定寬度,再設定margin、padding

width

:200px

margin:0px;

padding

:0px;

3、垂直居中(適合單獨一行垂直居中)

height和line-height設定成一樣即可

line-height:40px;

height

:40px;

4、內邊距方式居中

借助設定相同的上下內邊距,實現垂直居中效果,可以用在多行文字上

#ddiv

style>

id="d">多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 多行內容 div>

5、table方式(適用於居中)

首先通過display:table-cell

再借助於單元格的垂直居中來達到效果

#ddiv

style>

id="d">

src="">

div>

6、使用絕對定位和負外邊距對塊級元素居中(ps:必須提前知道被居中塊級元素的尺寸)

#box

#child

style>

id="box">

id="child">我要居中的內容div>

div>

7、使用translate居中(相容性不是很好)

#box

#child

style>

id="box">

id="child">我要居中的內容div>

div>

8、用計算的方式居中元素

.box

.child

style>

class="box">

class="child">我是要居中的內容div>

div>

css的幾種居中

首先,需要居中的元素分為三類 1.普通的div 浮動元素 設定了絕對定位的元素 關於普通的div的居中 這個相對來說是比較簡單的,直接用margin 0 auto div 對於普通元素,像上面這樣新增樣式即可 關於浮動元素的居中問題 這個問題困擾了我很久,因為浮動元素不像普通的元素,margin的任...

CSS水平居中的幾種方法

如果被設定元素為文字 等行內元素時,水平居中可以通過父元素設定text align center來實現。html style text align center 我是文字,哈哈,我想要在父容器中水平居中顯示。div body 當被設定元素為塊狀元素時用 text align center 就不起作用...

css垂直居中的幾種方法

1.lineheight方法 html class container id div1 src test.png 一行文字span div css container div1 div1 img效果 說明 設定了lineheight和容器高度相同,vertical align middle 需要知道...