当前位置:软件学堂 > 资讯首页 > 网络编程 > DIV+CSS > div水平垂直居中设置技巧

div水平垂直居中设置技巧

2012/9/20 15:05:42作者:佚名来源:网络

移动端

学习CSS+DIV的朋友,今天学无忧来教你们如何使用div水平垂直居中设置技巧,相信知道DIV的人对水平垂直居中并不陌生吧,但是对于那些刚学习的菜鸟来说,还是有很打帮助的!下面请看学无忧慢慢为大家进行详细的解说。

一、DIV水平居中设置技巧

在设计代码中使用margin-left:auto;margin-right:auto; 可以让你的div居中对齐。 在使用CSS的时候,在style属性中加入.style{margin-left:auto;margin-right:auto;},同时也可以使用缩写形式为: .style{margin:0 auto;}。

解释: 数字0,表示上下边距是0。然后左右居中。也可以按照需要设置成不同的值。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>水平垂直居中div演示效果</title>
<style type="text/css"> 
.align-center{ 
position:fixed;left:50%;top:50%;margin-left:width/2;margin-top:height/2;
} 
</style> 
</head> 
<body> 
<div class="align-center">
水平垂直居中div演示效果
</div> 
</body>
</html> 

或者不使用上面的代码,给body使用一个body{text-align:center;}属性值,让其全部居中。

二、DIV垂直居中设置技巧

关于垂直居中可以使用在CSS中代码为:position:fixed;left:50%;top:50%;margin-left:width/2;margin-top:height/2;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<title>水平垂直居中div演示效果</title> 
<style type="text/css"> 
.align-center{ 
position:fixed;left:50%;top:50%;margin-left:width/2;margin-top:height/2;
} 
</style> 
</head> 
<body> 
<div class="align-center">水平垂直居中div演示效果</div> 
</body> 
</html>

标签: 居中