A horizontal and vertically centered div window _jquery based on jquery

Source: Internet
Author: User
1, through the CSS to achieve horizontal center:
Copy Code code as follows:

. classname{
margin:0 Auto;
width:200px;
height:200px;
}

2, through the CSS to achieve horizontal center and vertical Center
Creating a horizontally centered and vertically centered div through CSS is a hassle, and you have to know the size of another div in advance:
Copy Code code as follows:

. classname{
width:300px;
height:200px;
Position:absolute;
left:50%;
top:50%;
margin:-100px 0 0-150px;
}

3, through jquery to achieve horizontal center and vertical center has been mentioned before, the CSS method is only applicable to a fixed size div, so to jquery to play a role:
Copy Code code as follows:

$ (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 approach is that you don't need to know how big a div is, but the downside is that it can only be implemented through JavaScript.

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.