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

css 实现DIV水平垂直居中于屏幕_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:26:061652browse

 

css如何将div实现全屏水平垂直居中,本章节介绍一下如何将一个div元素在整个网页内实现水平垂直居中效果,代码是最有说服力的,直接看代码。

代码如下:

<!DOCTYPE html> <html> <head> <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> </head> <body> <div id="thediv"></div></body> </html>

在线运行

 

以上代码将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