JQuery provides us with easy and simple control methods. For example, we can use $ (document) to set a horizontally vertical center layer ). width () and $ (document ). height () to obtain the width and height of the window. Then, a simple calculation is performed to center the layer horizontally and vertically.
Horizontal vertical center div jquery
<Html>
<Head>
<Script src = "jquery. js"> </script>
<Style>
# Nw {border: 1px solid #000; background: # ccc; height: 220px; width: 520px ;}
</Style>
</Head>
<Body>
<Div id = "nw"> I am a center layer! </Div>
</Body>
</Html>
<Script>
$ (Function (){
Tutorial ('{nw'}.css tutorial ({'position': 'absolute ', 'left' :( $ (document ). width ()-520)/2, 'top' :( $ (document ). height ()-220)/2 });
});
</Script>
Method 20
Jquery. fn. center = function (params ){
Var options = {
Vertical: true,
Horizontal: true
}
Op = jquery. extend (options, params );
Return this. each (function (){
Var $ self = jquery (this );
Var width = $ self. width ();
Var height = $ self. height ();
Var paddingtop = parseint($self.css ("padding-top "));
Var paddingbottom = parseint($self.css ("padding-bottom "));
Var bordertop = parseint($self.css ("border-top-width "));
Var borderbottom = parseint($self.css ("border-bottom-width "));
Var mediaborder = (bordertop + borderbottom)/2;
Var mediapadding = (paddingtop + paddingbottom)/2;
Var positiontype = paiself.parent().css ("position ");
Var halfwidth = (width/2) * (-1 );
Var halfheight = (height/2) * (-1)-mediapadding-mediaborder;
Var cssprop = {
Position: 'abort'
};
If (op. vertical ){
Cssprop. height = height;
Cssprop. top = '123 ';
Cssprop. margintop = halfheight;
}
If (op. horizontal ){
Cssprop. width = width;
Cssprop. left = '20140901 ';
Cssprop. marginleft = halfwidth;
}
If (positiontype = 'static '){
$Self.parent().css ("position", "relative ");
}
$Self.css (cssprop );
});
};
Method 3
$ ("Element"). center (); // vertical and horizontal
$ ("Element"). center ({horizontal: false // only vertical });
Download the plug-in: jquery.demo.js.txt (change the extension name by yourself)
Summary
Jquery provides us with easy and simple control methods. For example, we can use $ (document) to set a horizontally vertical center layer ). width () and $ (document ). height () to obtain the width and height of the window. Then, a simple calculation is performed to center the layer horizontally and vertically.