當(dāng)前位置:軟件學(xué)堂 > 資訊首頁(yè) > 網(wǎng)絡(luò)編程 > DIV+CSS > div水平垂直居中設(shè)置技巧

div水平垂直居中設(shè)置技巧

2012/9/20 15:05:42作者:佚名來源:網(wǎng)絡(luò)

移動(dòng)端

學(xué)習(xí)CSS+DIV的朋友,今天學(xué)無憂來教你們?nèi)绾问褂?strong>div水平垂直居中設(shè)置技巧,相信知道DIV的人對(duì)水平垂直居中并不陌生吧,但是對(duì)于那些剛學(xué)習(xí)的菜鳥來說,還是有很打幫助的!下面請(qǐng)看學(xué)無憂慢慢為大家進(jìn)行詳細(xì)的解說。

一、DIV水平居中設(shè)置技巧

在設(shè)計(jì)代碼中使用margin-left:auto;margin-right:auto; 可以讓你的div居中對(duì)齊。 在使用CSS的時(shí)候,在style屬性中加入.style{margin-left:auto;margin-right:auto;},同時(shí)也可以使用縮寫形式為: .style{margin:0 auto;}。

解釋: 數(shù)字0,表示上下邊距是0。然后左右居中。也可以按照需要設(shè)置成不同的值。

<!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使用一個(gè)body{text-align:center;}屬性值,讓其全部居中。

二、DIV垂直居中設(shè)置技巧

關(guān)于垂直居中可以使用在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>

標(biāo)簽: div  居中  設(shè)置