Home >Web Front-end >Front-end Q&A >How to center an element in JavaScript

How to center an element in JavaScript

藏色散人
藏色散人Original
2021-06-27 11:17:333135browse

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';   
}

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!

Statement:
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