已知/未知宽高的浮动元素水平居中对齐 和 图片水平垂直居中对齐

一、已知宽高的浮动元素水平垂直居中对齐

效果:


样式CSS:

 1 <style>
 2     .parent{
 3         position:relative;
 4         border:2px solid #0f0;
 5     }
 6     .child{
 7         float:left;
 8         background-color:#6699ff;
 9         width:200px;
10         height:200px;
11         border:2px solid #f00;
12         position:absolute;
13         top:50%;
14         left:50%;
15         margin-top:-100px;
16         margin-left:-100px;
17     }
18  </style>
模板HTML:
1 <body>
2     <div class="parent">
3         <div class="child"></div>
4     </div>
5  </body>
二、未知宽高的浮动元素水平垂直居中对齐

效果:


样式CSS:

 1 <style>
 2     .parent{
 3         position:relative;
 4         border:2px solid #0f0;
 5     }
 6 
 7     .child{
 8         float:left;
 9         background-color:#6699ff;
10         width:260px;//元素宽高随便设定
11         height:260px;
12         border:2px solid #f00;
13 
14         margin:auto;
15         position:absolute;
16         top:0;
17         left:0;
18         bottom:0;
19         right:0;
20     }
21  </style>
模板HTML:
1 <body>
2     <div class="parent">
3         <div class="child"></div>
4     </div>
5  </body>
三、图片的水平垂直居中

1.效果 

 

 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>图片垂直居中</title>
 6 </head>
 7 <body>
 8 <style>
 9     .test_box {
10         width: 200px;
11         height: 200px;
12         overflow: hidden;
13         text-align: center;
14         font-size: 0;
15         border: 1px solid #ff0000;
16     }
17 
18     .test_box .hook {
19         display: inline-block;
20         width: 0;
21         height: 100%;
22         overflow: hidden;
23         margin-left: -1px;
24         font-size: 0;
25         line-height: 0;
26         vertical-align: middle;
27     }
28 
29     .test_box img {
30         vertical-align: middle;
31         border: 0 none;
32     }
33 </style>
34 <div class="test_box">
35     <span class="hook"></span>
36     <a href="#" target="_blank"><img src="22.jpg" alt=""/></a>
37 </div>
38 
39 </body>
40 </html>

 

 

2.效果:


样式CSS:

 1 <style>
 2         .container{
 3             display:table-cell;
 4             text-align:center;
 5             vertical-align:middle;
 6             width:500px;
 7             height:300px;
 8             border:2px solid #f00;
 9         }
10 
11         img{
12             width:200px;
13             height:200px;
14             border:2px solid #0f0;
15         }
16 
17   </style>
模板HTML:
1 <div class="container">
2     <img src="watermelon.jpg" alt="">
3  </div>
posted @ 2017-08-13 14:22  Sun·傲宇  阅读(237)  评论(0编辑  收藏  举报