Home  >  Article  >  Web Front-end  >  Div is displayed centered in the browser_html/css_WEB-ITnose

Div is displayed centered in the browser_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 12:15:491112browse

Dear prawns, how can I center the DIV in the browser? If you set its margins, it will be different if you change the size of the monitor. Thank you! ! !


Reply to discussion (solution)

Set CSS:

div{
margin-left:auto;
margin-right:auto;
}

This requires dynamically setting the position of the Div
style="position:absolute;top={1}px;left={2}px;"
As above, your Div The style needs to be set to this, but top and left need to be calculated dynamically.
The problem is to dynamically obtain the size of the browser window. So the solution is as follows:

<html> <head>     <title>DIV居中显示</title>         <script type="text/javascript"> 		var setDivCenter = function(divId){			var oDiv = document.getElementById(divId);			oDiv.style.position = "absolute";			oDiv.style.top = (document.body.offsetHeight - 150) / 2 + "px";//这个150是div的高度			oDiv.style.left = (document.body.offsetWidth - 200) / 2 + "px";//这个200是div的宽度		};	        </script> </head> <body onload="setDivCenter('dvCenter')"> 	<div id="dvCenter" style="width:200px;height:150px;background-color:red;">		我在浏览器的中间	</div></body> </html> 

I just wrote it and it has passed the test~~

Thank you very much! ! ! ! ! !

I want to see how to solve it

Let’s see how to solve it

2nd floor is awesome

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