在CSS中,我们水平和垂直地对齐项目。使用了各种方法和技术来居中,注意左右边距,等等。
使用方法讨论如下:
margin: auto:此属性用于将块元素对齐到中心。
示例1:
<!DOCTYPE html>
<html>
<head>
<style>
.center {
margin: auto;
width: 60%;
border: 3px solid #73AD21;
padding: 10px;
}
</style>
</head>
<body>
<h1 style = "color:green;">
srcmini
</h1>
<h2>Center Align Elements</h2>
<div class = "center">
This is div element on which
margin auto is used to horizontally
align it into center
</div>
</body>
</html>
注意:除非声明了!DOCTYPE, 否则在IE8中不能使用margin:auto。
输出:

position: absolute;
我们可以使用此属性对齐项目。
示例2:
<!DOCTYPE html>
<html>
<head>
<style>
.right {
position: absolute;
right: 0px;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
</style>
</head>
<body>
<h1 style = "color:green;">
srcmini
</h1>
<h2>Right Align</h2>
<div class = "right">
<p>
Absolute positioned
elements can overlap other
elements.
</p>
</div>
</body>
</html>
输出:

text-align: center;
我们可以将任何用HTML编写的文本对齐在中间。我们可以在各种标记中使用此属性。
示例3:
<!DOCTYPE html>
<html>
<head>
<style>
.center {
text-align: center;
border: 3px solid green;
}
</style>
</head>
<body>
<h1 style="color:green;
text-align: center;">
srcmini
</h1>
<h2>BOTH TEXTS ARE AT CENTER</h2>
<div class = "center">
<p>This text is centered.</p>
</div>
</body>
</html>
输出:

padding:
要垂直对齐项目, 我们可以使用填充。
示例4:
<!DOCTYPE html>
<html>
<head>
<style>
.center {
padding: 70px 0;
border: 3px solid green;
}
</style>
</head>
<body>
<h1 style="color:green;
text-align:center;">
srcmini
</h1>
<h2>Center Vertically</h2>
<div class = "center">
<p>This is vertically centered.</p>
</div>
</body>
</html>
输出:

填充和文本对齐;
结合使用padding和text-align:居中垂直和水平对齐文本。
示例5:
<!DOCTYPE html>
<html>
<head>
<style>
.center {
padding: 70px 0;
border: 3px solid green;
text-align: center;
}
</style>
</head>
<body>
<h1 style = "color:green;">
srcmini
</h1>
<p>Here we use padding and text-align
to center the div element vertically
and horizontally:</p>
<div class = "center">
<p>This text is vertically
and horizontally centered.</p>
</div>
</body>
</html>
输出:
