JQuery-based horizontal and vertical center div window _ jquery-js tutorial

Source: Internet
Author: User
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:

The Code is as follows:


. ClassName {
Margin: 0 auto;
Width: 200px;
Height: 200px;
}


2. Implement horizontal and vertical center through css
Creating a horizontal and vertical center p through css is a troublesome task. You must know the size of another p in advance:

The Code is as follows:


. 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 fixed-size p, so jQuery plays a role:

The Code is as follows:


$ (Window). resize (function (){
Certificate ('.classname'}.css ({
Position: 'absolute ',
Left: ($ (window). width ()-$ ('. classname'). outerWidth ()/2,
Top: ($ (window). height ()-$ ('. classname'). outerHeight ()/2 + $ (document). scrollTop ()
});
});
// Initialize the Function
$ (Window). resize ();


The advantage of this method is that you do not need to know the size of p, but the disadvantage is that it can only be implemented through JavaScript.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.