div Vertical/Horizontal Center 2 (div width and height are dynamic)

Source: Internet
Author: User

<!doctype html>
<meta charset= "Utf-8" >
<title> block element div-Vertical/Horizontal Center (dynamic) </title>
<script type= "Text/javascript" src= "Js/jquery.js" ></script>
<script type= "Text/javascript" >
$ (document). Ready (function () {
Resize event occurs when resizing a browser window
$ (window). Resize (function () {$ (". Mydiv"). CSS ({
Position: "Absolute",
Left: ($ (window). Width ()-$ (". Mydiv"). Outerwidth ())/2,
Top: ($ (window). Height ()-$ (". Mydiv"). Outerheight ())/2});
});
$ (function () {
$ (window). Resize ();
});
});
$ (function () {////When the page refreshes, the Resize event occurs (you can delete the three-line program and test it Yourself)
$ (window). Resize ();
});
</script>
<body>
<div class= "mydiv" > Oh ha ha ha ha ha ha ha ha ha ha ha ha hehe ha ha ha hehe oh oh hehe ha ho, huh, haha, </div>
</body>
Tip: Run this code to download the jquery plugin
Code principle: Through jquery set div css, get div's left, margin offset, margin offset algorithm is to use the width of the page window minus the div width, the resulting value divided by 2 is the left offset, the right offset algorithm is the same

Div Vertical/Horizontal Center 2 (div width and height are dynamic)

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.