有多种方法可以将 CSS 图像和文本在父元素上垂直居中并在中心线上对齐
1。使用辅助弯曲轴垂直居中
1。设置次轴上的中心对齐(从上到下)(align-elements: center;)可以
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Document</title>
6
7 <style>
8
9 .a{
10 width: 200px;
11 height: 200px;
12 background-color: #bfa;
13 /*行高,使文字在父元素中垂直居中*/
14 /*line-height: 200px;*/
15
16 display: flex;
17 /*justify-content: center;*/
18 /*副轴对齐方式*/
19 align-items: center;
20 }
21
22 img{
23 /*margin-bottom: -16px;*/
24 /*和文字中线对齐*/
25 /*vertical-align: middle;*/
26 width: 20%;
27 height: 20%;
28
29 }
30
31 </style>
32 </head>
33 <body>
34 <div class="a">
35
36 <img alt="">
37 <span>nioifhiughi</span>
38
39 </div>
40 </body>
41 </html>效果
![]()
其次,使用垂直对齐: center ;
1。父元素设置行高让文本垂直居中对齐,然后图片对齐设置为vertical-align: center;图像和文本的中心线对齐
2。图片没有设置为垂直对齐:居中,图片和文字的中心线没有对齐。
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Document</title>
6
7 <style>
8
9 .a{
10 width: 200px;
11 height: 200px;
12 background-color: #bfa;
13 /*行高,使文字在父元素中垂直居中*/
14 line-height: 200px;
15
16 /*display: flex;*/
17 /*justify-content: center;*/
18 /*副轴对齐方式*/
19 /*align-items: center;*/
20 }
21
22 img{
23 /*margin-bottom: -16px;*/
24 /*和文字中线对齐*/
25 vertical-align: middle;
26 width: 20%;
27 height: 20%;
28
29 }
30
31 </style>
32 </head>
33 <body>
34 <div class="a">
35
36 <img alt="">
37 <span>nioifhiughi</span>
38
39 </div>
40 </body>
41 </html>
第三,在图像上设置margin-bottom,注意负值。
1。当图像没有指定margin-bottom时,图像和文本的中心线不对齐。此时,将margin-bottom设置为负数,图像就会慢慢向下移动。当图像和文字的中心线对齐时,就OK了。
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Document</title>
6
7 <style>
8
9 .a{
10 width: 200px;
11 height: 200px;
12 background-color: #bfa;
13 /*行高,使文字在父元素中垂直居中*/
14 line-height: 200px;
15
16 /*display: flex;*/
17 /*justify-content: center;*/
18 /*副轴对齐方式*/
19 /*align-items: center;*/
20 }
21
22 img{
23 margin-bottom: -16px;
24 /*和文字中线对齐*/
25 /*vertical-align: middle;*/
26 width: 20%;
27 height: 20%;
28
29 }
30
31 </style>
32 </head>
33 <body>
34 <div class="a">
35
36 <img alt="">
37 <span>nioifhiughi</span>
38
39 </div>
40 </body>
41 </html>不均匀效果
![]()
对齐效果
![]()
上面是css,图片和文字在父元素中垂直居中,图片和文字对齐。 。
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
code前端网