How to center an element in JavaScript

藏色散人
Release: 2021-06-27 11:17:33
Original
3065 people have browsed it

How to set the element to be centered in JavaScript: first create a front-end sample file; then set the position attribute value of the specified element to absolute; finally add "οnlοad="center();"" to the body.

How to center an element in JavaScript

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

How to center an element in JavaScript?

Javascript method to control the centering of an element

For example, if you want to control the centering of an element with the ID of div1, first set the position attribute value of the element to absolute, and add a οnlοad="center();"

Code:

function center() {   
    var divId=document.getElementById('div1');   
    divId.style.left=(document.documentElement.clientWidth-divId.clientWidth)/2+'px';   
    divId.style.top=(document.documentElement.clientHeight-divId.clientHeight)/2+'px';   
}
Copy after login

This way the div can be centered, provided that you comply with w3c specifications, this works in both ie and firefox Tested. If you remove the unit ("px"), Firefox will make you faint, haha~~

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to center an element in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!