CSS 水平对齐(Horizontal Align)

CSS 水平对齐(Horizontal Align)


块元素对齐

块元素是一个元素,占用了全宽,前后都是换行符。

块元素的例子:

  • <h1>
  • <p>
  • <div>

中心对齐,使用margin属性

块元素可以把左,右页边距设置为"自动"对齐。

Note: 在IE8中使用margin:auto属性无法正常工作,除非声明 !DOCTYPE

margin属性可任意拆分为左,右页边距设置自动指定,结果都是出现居中元素:

<!DOCTYPE html>
<html>
<head>
<title>test</title> 
<style>
.center
{
	margin-left:auto;
  margin-right:auto;
	width:70%;
	background-color:#b0e0e6;
}
</style>
</head>

<body>
<div class="center">
<p>hehe</p>
<p>haha</p>
</div>
<p><b>注意: </b>使用 margin:auto 无法兼容 IE8, 除非 !DOCTYPE 已经声明.</p>
</body>
</html>

使用position属性设置左,右对齐

元素对齐的方法之一是使用绝对定位: 

<!DOCTYPE html>
<html>
<head>
<title>test</title> 
<style>
.right
{
	position:absolute;
	right:0px;
	width:300px;
	background-color:#b0e0e6;
}
</style>
</head>

<body>
<div class="right">
<p>hehe</p>
<p>haha</p>
</div>
</body>
</html>

注意:绝对定位与文档流无关,所以它们可以覆盖页面上的其它元素。


使用float属性设置左,右对齐

使用float属性是对齐元素的方法之一:

<!DOCTYPE html>
<html>
<head>
<title>test</title> 
<style>
.right
{
	float:right;
	width:300px;
	background-color:#b0e0e6;
}
</style>
</head>

<body>
<div class="right">
<p>hehe</p>
<p>haha</p>
</div>
</body>
</html>

  

猜你喜欢

转载自injavawetrust.iteye.com/blog/2335240