Home  >  Article  >  Web Front-end  >  css 实现DIV水平垂直居中于屏幕

css 实现DIV水平垂直居中于屏幕

WBOY
WBOYOriginal
2016-06-01 09:53:131146browse

代码如下:

<code class="language-html"> 
 
 

<title>css 实现DIV水平垂直居中于屏幕</title>
<style type="text/css"> 
body{ 
  margin:0px; 
  padding:0px; 
} 
#thediv{
  width:100px;
  height:100px;
  background:green;
  position:absolute;
  left:50%;
  top:50%;
  margin-left:-50px;
  margin-top:-50px;
}
</style> 
 
 
<div id="thediv"></div>
 
</code>

在线运行

以上代码将div在网页中实现了全屏居中效果,下面简单介绍一下它的实现过程。

实现原理:

将div元素设置为绝对定位,然后设置它的left和right属性值分别为50%,这个时候div并没有居中,居中的是div的左上角,所以我们还需要再将其向上和向左拉动一定的距离即可,这个距离分别是高度和宽度的一半。

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