首页 > Web开发 > 详细

利用css来让一个div在页面中垂直居中的方法

时间:2017-01-16 19:38:25      阅读:228      评论:0      收藏:0      [点我收藏+]

 

一、如何让一个div在页面中垂直居中(请至少列出三种)

 

1.距离页面窗口左边框和上边框的距离设置为50%,这个50%就是指页面窗口的宽度和高度的50%,最后将该DIV分别左移和上移,左移和上移的大小就是该DIV宽度和高度的一半。

width:300px; 

 height:200px; 

 position:absolute;

 left:50%

 top:50%;  

 margin:-100px 0 0 -150px ;

2.使用jquery代码

 $(window).resize(function(){ 

   $(".mydiv").css({ 

     position: "absolute", 

     left: ($(window).width() - $(".div").outerWidth())/2, 

     top: ($(window).height() - $(".div").outerHeight())/2 

   });        

}); 

3.使用绝对定位;top,bottom,left,right分别都为零

父元素设置为:

  width:800px;

           height:500px;

           border:2px solid #000;

           position:relative;

子元素设置为:

  width:200px;

            height:200px;

            margin: auto;

            position: absolute;

            top: 0; left: 0; bottom: 0; right: 0;

            

 

4.(此方法暂时只能设置元素在父级元素中垂直居中,还没有实现水平居中),使用display:table-cell

父元素设置为:

width:800px;

height:500px;

border:2px solid #000;

display:table-cell;

vertical-align:middle;

text-align: center;

子元素设置为:

 

width:200px;

height:200px;

 

display:inline-block;

5.实用弹性布局的方式来解决

父级元素设置为

width:800px;

height:500px;

border:2px solid #000;

display:flex;

justify-content:center;

align-items:center;

 

子元素设置为:

width: 200px;

height: 200px;

background-color: red;

利用css来让一个div在页面中垂直居中的方法

原文:http://www.cnblogs.com/fireporsche/p/6290637.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!