前端開發過程中,經常遇到這樣的布局“同一行的圖片和文字都垂直居中”,如下圖所示:

現將幾種實現方法總結如下:
html代碼:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<
body
>
<
div
class
=
"line methodOne"
>
<
img
src
=
"images/logo.png"
alt
=
"圖片"
/>
<
span
>我是文字</
span
>
</
div
>
<
div
class
=
"line methodTwo"
>
<
img
src
=
"images/logo.png"
alt
=
"圖片"
/>
<
span
>我是文字</
span
>
</
div
>
<
div
class
=
"line methodThree"
>
<
img
src
=
"images/logo.png"
alt
=
"圖片"
/>
<
span
>我是文字</
span
>
</
div
>
<
div
class
=
"line methodFour"
>
<
img
src
=
"images/logo.png"
alt
=
"圖片"
/>
<
span
>我是文字</
span
>
</
div
>
</
body
>
|
css代碼:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
* {
margin
:
0
;
padding
:
0
;
}
body {
padding
:
0
10px
;
}
.line {
font-size
:
20px
;
border-bottom
:
1px
solid
#dddddd
;
}
.line img {
width
:
80px
;
height
:
80px
;
border-radius:
50%
;
margin-right
:
20px
;
}
|
方法1:padding+line-height
|
1
2
3
4
5
6
7
8
|
.methodOne {
padding
:
20px
0
;
}
.methodOne span {
line-height
:
80px
;
vertical-align
:
top
;
}
|
方法2:display:flex;+align-items:center;
|
1
2
3
4
5
|
.methodTwo {
display
: flex;
height
:
120px
;
align-items:
center
;
}
|
注意:父級元素設置display:flex;后,子元素float失效。
方法3:padding+vertical-align:middle;
|
1
2
3
4
5
6
7
|
.methodThree {
padding
:
20px
0
;
}
.methodThree * {
vertical-align
:
middle
;
}
|
方法4:line-height+vertical-align:middle;
|
1
2
3
4
5
6
7
|
.methodFour {
height
:
120px
;
line-height
:
120px
;
}
.methodFour *{
vertical-align
:
middle
;
}
|
方法5:使用 Flexbox 實現子元素的居中效果,只需三行代碼:
@mixin center-children {
display: flex;
justify-content: center;
align-items: center;
}
由於 Flexbox 還是比較新的屬性,那么添加上相關的瀏覽器前綴的話,會讓它擁有更廣泛的兼容性。
.parent {
@include center-children;
}
正如你料想的那樣,就這么簡單我們就實現了:
.parent {
display: flex;
justify-content: center;
align-items: center;
}
