How to make an unknown height div vertically centered:
There are a variety of ways to align Div vertically, and you can use CSS to center the Div vertically in the parent element, but it is difficult to align it vertically in the parent element without knowing the div height, because browser compatibility is involved, Here is an introduction to the unknown height of the div by JS in the parent element vertically centered, the code is as follows:
<!DOCTYPE HTML><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /><Metaname= "Author"content= "http://www.51texiao.cn/" /><title>Ant Tribe</title><styletype= "Text/css">#parent{width:200px;Height:200px;Background-color:Red;Overflow:Hidden;}#children{width:60px;Height:60px;Background-color:Green;margin:0px Auto;}</style><Scripttype= "Text/javascript">window.onload=function(){ varParenth=document.getElementById ("Parent"). offsetheight; varchildrenh=document.getElementById ("Children"). offsetheight; document.getElementById ("Children"). Style.margintop=((Parenth-childrenh)/2) + "px";}</Script></Head><Body><DivID= "Parent"> <DivID= "Children"></Div></Div></Body></HTML>
The above code implements the child element in the parent element vertical Center effect, the code is relatively concise, also does not have the CSS to be compatible with each browser's trouble.
Here's the implementation process:
I. Principle of implementation:
The height of the parent and child elements is obtained by JS, so that the child elements can be centered in the parent element by using the upper margin of the JS settings child element.
Two. Code Analysis:
1.document.getelementbyid ("parent"). Offsetheight Gets the height of the parent element.
2.document.getelementbyid ("Children"). Offsetheight Gets the height of the child element.
3.document.getelementbyid ("Children"). Style.margintop you can set the top margin of the child elements.
4.PARENTH-CHILDRENH)/2, the height of the parent element minus the height of the child element, divided by 2, is exactly where the child element is centered vertically in the parent element.
Original address: http://www.51texiao.cn/javascriptjiaocheng/2015/0405/136.html
How to make an unknown height div vertically centered