面试小结:html/css实现元素居中

  园子开辟好长一段时间了,一直都没有开始写一篇文章。今天面试的时候提及到写个技术博客,于是产生了七个月以来的第一篇博文。从这一篇文章开始,计划将此博客用于个人总结和记录,写下学习过程中遇到的问题和解决方法。


  唠叨完,开始正文内容,如何用html/css使得未知宽高的元素水平垂直居中?这也是今天在笔试时候遇到的一道题目。下面给出几种解决方法。

1.利用vertical-align:middle

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7         body{margin: 0;}
 8         .father{width: 100%;height: 100%;position: fixed;left: 0;top: 0;text-align: center;font-size: 0;/*设置font-size为了消除代码换行所造成的空隙*/background:rgba(0,0,0,0.5); }
 9         .daughter{vertical-align: middle;}/*实现daughter居中*/
10         .son{vertical-align: middle;display:inline-block;height: 100%;}
11     </style>
12 </head>
13 <body>
14 <div class = "father">
15     <div class="son"></div>
16     <img class = "daughter" src="1.jpg" alt="我要居中">
17 </div>
18 </body>
19 </html>

2.使用transform实现

1 <style>
2     body{margin: 0;}
3     .father {position: absolute; left:50%; top:50%; -webkit-transform:translate(-50%,-50%); transform:translate(-50%,-50%);background:rgba(0,0,0,0.5); }
4 </style>
5 <div class="father">
6     <img src="1.jpg">
7 </div>

3.弹性盒模型

1 <style>
2     body{margin: 0;}
3     .father{position:fixed; width:100%; height:100%; background:rgba(0,0,0,0.5); left:0px; top:0px;display:flex;justify-content:center;align-items:center;}
4 </style>
5 
6 
7 <div class="father">
8         <img src="1.jpg">
9 </div>

4.用表格布局

 1 <style>
 2 *{margin:0px; padding:0px;}
 3 table {position:absolute; width:100%; height:100%; text-align:center; background:rgba(0,0,0,0.5);}
 4 .daughter {display:inline-block;}
 5 </style>
 6 <table>
 7     <tr>
 8         <td>
 9             <div class="daughter">
10                 <img src="1.jpg">
11             </div>
12         </td>
13     </tr>
14 </table>

欢迎指导~~2015-12-12 17:16:44 

原文地址:https://www.cnblogs.com/crystalmoore/p/5041522.html