css,圖片和文字在父元素垂直居中,且圖片和文字在中線對齊排列的幾種方式


一,用flex的副軸來垂直居中對齊

1.副軸(由上到下)設置居中對齊(align-items: 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 src="img/11.jpg" alt="">
37     <span>nioifhiughi</span>
38     
39     </div>
40 </body>
41 </html>

效果

 

 

二,利用vertical-align: middle ;

1.父元素設置行高,使文字垂直居中對齊,然后對圖片設置vertical-align: middle ;使圖片和文字的中線對齊

2.圖片沒設置vertical-align: middle ,圖片和文字的中線不齊。

 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 src="img/11.jpg" 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 src="img/11.jpg" alt="">
37     <span>nioifhiughi</span>
38     
39     </div>
40 </body>
41 </html>

不齊效果

 

 一起齊的效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM