如何让DIV相对于body水平和垂直居中_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:50:03
Original
1326 people have browsed it

我们在设计页面的时候,经常要把DIV居中显示,而且是相对页面窗口水平和垂直方向居中显示,如让登录窗口居中显示。我们传统解决的办法是用纯CSS来让DIV居中。在本文中,我将给大家讲述如何用CSS和jQuery两种方法让DIV水平和垂直居中。

CSS让DIV水平居中

说明,本文中所指的DIV包括HTML页面中所有的元素。

让一个DIV水平居中,直接用CSS就可以做到。只要设置了DIV的宽度,然后使用margin设置边距0 auto,CSS自动算出左右边距,使得DIV居中。

<strong>.mydiv</strong>{        margin:0 auto;        width:300px;        height:200px;    }   
Copy after login

但是如果要使DIV垂直方向也居中,恐怕CSS需要修改了。

CSS实现水平和垂直居中

要让DIV水平和垂直居中,必需知道该DIV得宽度和高度,然后设置位置为绝对位置,距离页面窗口左边框和上边框的距离设置为50%,这个50%就是指页面窗口的宽度和高度的50%,最后将该DIV分别左移和上移,左移和上移的大小就是该DIV宽度和高度的一半。

<strong>.mydiv</strong>{     width:300px;      height:200px;      position:absolute;      left:50%;      top:50%;      margin:-100px 0 0 -150px  }  
Copy after login

该方法使用普遍,但是前提是必需设置DIV的宽度和高度。如果当页面DIV宽度和高度是动态的,比方说需要弹出一个DIV层并且要居中显示,DIV的内容是动态的,所以宽度和高度也是动态的,这时需要用jQuery可以解决居中。

jQuery实现水平和垂直居中

jQuery实现水平和垂直居中的原理就是通过jQuery设置DIV的CSS,获取DIV的左、上的边距偏移量,边距偏移量的算法就是用页面窗口的宽度减去该DIV得宽度,得到的值再除以2即左偏移量,右偏移量算法相同。注意DIV的CSS设置要在resize()方法中完成,就是每次改变窗口大小时,都要执行设置DIV的CSS,代码如下:

$(window).resize(<strong>function</strong>()<strong>{</strong>      $(".mydiv").css(<strong>{</strong>          position: "absolute",          left: ($(window).width() - $(".mydiv").outerWidth())/2,          top: ($(window).height() - $(".mydiv").outerHeight())/2      <strong>}</strong>);         <strong>}</strong>);  
Copy after login

此外在页面载入时,就需要调用resize()。

$(<strong>function</strong>()<strong>{</strong>      $(window).resize();  <strong>}</strong>);  
Copy after login

此方法的好处就是不需要知道DIV的具体宽度和高度大小,直接用jQuery就可以实现水平和垂直居中,而且兼容各浏览器,这个方法在很多的弹出层效果中应用。

 ps:如果该div的宽度大于页面的宽度,那么需要对body添加一个css

 

注:本文来源于helloweba.com,原文地址为http://www.helloweba.com/view-blog-93.html

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!