When building a webpage layout, we often face a problem, that is, to align a div horizontally and vertically. Although there are several ways to achieve it, my favorite method is introduced today, implemented through CSS and jquery.
1. Implement horizontal center through CSS:
. Classname {
Margin : 0 auto ;
Width : 200px ;
Height : 200px ;
}
2. Implement horizontal and vertical center through CSS
Creating a horizontal and vertical Div using CSS is a troublesome task. You must know the size of another DIV in advance:
. Classname {
Width : 300px ;
Height : 200px ;
Position : Absolute ;
Left : 50% ;
Top : 50% ;
Margin : -100px 0 0-150px ;
}
3. Using jquery to implement horizontal and vertical center as mentioned above, CSS is only applicable to Div with fixed size, so jquery plays a role: $ (Window). Resize ( Function (){
$ ( ' . Classname ' ).Css ({
Position: ' Absolute ' ,
Left: ($ (window). Width () - $ ( ' . Classname ' ). Outerwidth ()) / 2,
Top: ($ (window). Height () - $ ( ' . Classname ' ). Outerheight ()) / 2 + $ (document). scrolltop ()
});
});
// Initialization Function
$ (Window). Resize ();
The advantage of this method is that you do not need to know the size of the DIV, but the disadvantage is that it can only be implemented through JavaScript.