图片和文字上下左右居中

父级:relative

子级:absolute绝对定位,并设置left、top,设置margin来减去居中元素的1/2宽和1/2高。

效果图:

源码如下,粘贴到本地即可运行看到效果:左侧的图片和暂无数据文字居中。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title> DEMO:内容上下左右居中 </title>
 5     <meta name="keywords" content="/*
 6 1.How To Use?
 7     使用absolute通常是:父级定义position:relative定位,子级定义position:absolute绝对定位属性,并且子级使用left或right和top或bottom进行绝对定位
 8 2.What's the different?
 9     absolute : 将对象从文档流中拖出,使用left,right,top,bottom等属性进行绝对定位。而其层叠通过css z-index属性定义。此时对象不具有边距,但仍有补白和边框.
10     relative : 对象不可层叠,但将依据left,right,top,bottom等属性在正常文档流中偏移位置
11  */"/>
12 </head>
13 <style type="text/css">
14 .content-box{
15      1094px;height: 372px;
16 }
17 .border-left {
18     float: left;
19     /*父级需使用relative*/
20     position: relative;
21     background-color: #f8f8f8;
22     height: 100%;
23      794px;
24 }
25 
26 .left-box {
27     /*关键点:子级使用绝对定位,并设置left、top*/
28     position: absolute;
29     left: 50%;
30     top: 50%;
31     /*用margin减去居中元素的1/2宽和1/2高*/
32     margin-top: -83px;
33     margin-left: -63px;
34 }
35 
36 .left-box div {
37      124px;
38     height: 40px;
39     line-height: 40px;
40     text-align: center;
41 }
42 
43 .border-right {
44      300px;
45     float: right;
46     height: 100%;
47     background: #feced7;
48     text-align: center;
49 
50 }
51 </style>
52 
53 <body>
54     <div class="content-box">
55         <div class="border-left">
56             <div class="left-box">
57                 <img src="nodata_icon.png">
58                 <div>暂无数据</div>
59             </div>
60         </div>
61         <div class="border-right">
62             <div>the right border</div>
63         </div>
64     </div>
65 </body>
66 
67 </html>
View Code
原文地址:https://www.cnblogs.com/xxiaonian/p/6667569.html