Home >Web Front-end >Front-end Q&A >How to center an element in JavaScript
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.
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'; }
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!