Home  >  Article  >  Web Front-end  >  调整窗口大小也能够实现div水平垂直居中代码实例_html/css_WEB-ITnose

调整窗口大小也能够实现div水平垂直居中代码实例_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:29:191115browse

调整窗口大小也能够实现div水平垂直居中代码实例:
将一个div在窗口内实现居中效果,基本上没有什么难度,具体可以参阅CSS实现div屏幕居中效果代码一章节。 
但是有时候我们可能会有这样的需求,就是在调整窗口大小的情况下也能够实现div垂直水平居中效果,下面通过代码实例做一下简单介绍,代码如下:

 

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>蚂蚁部落</title>  <style type="text/css">*{  margin:0px;  padding:0px;} #thediv{  width:200px;  height:100px;  background:green;  position:absolute;  left:50%;  top:50%;  margin-left:-100px;  margin-top:-50px;}</style>  </head> <body><div id="thediv"></div></body> </html>

 

上面的代码实现了我们的要求,因为div采用的是绝对定位,并且采用百分比的方式来确定div的基本位置,不是采用固定尺寸的方式,然后在使用外边距向回调整一定的距离,这样就实现了居中效果,同时调整浏览器窗口也会实现一直居中的效果。

原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=14354

更多内容可以参阅:http://www.softwhy.com/divcss/

 

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