CSS 水平,垂直,居中对齐

使用CSS属性实现各种对齐,比如左对齐,居中对齐,右对齐,垂直居中对齐等

方法一: 使用float属性设置左右对齐

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>实例</title> 
  <title>php.cn</title>
    <style type="text/css">
      .divcss5-left{float:left;width:250px;height:50px;border:1px solid #F00} 
    </style>
</head>
<body>
<div class="divcss5-left">此DIV靠左对齐显示</div> 
</body>
</html>

方法二:使用margin属性进行中心对齐

只需要对要居中对齐的样式加 margin:0 auto

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>实例</title> 
  <title>php.cn</title>
    <style type="text/css">
      .divcss5-cent{margin:0 auto;width:250px;height:50px;border:1px solid #F00} 
    </style>
</head>
<body>
<div class="divcss5-cent">此DIV居中对齐显示</div> 
</body>
</html>

方法三:使用position属性设置左,右对齐

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>实例</title> 
  <title>php.cn</title>
    <style type="text/css">
      .divcss5-cent
        {
         position:absolute;
           right:0px;
           width:250px;
           height:50px;
           border:1px solid #F00
        } 
    </style>
</head>
<body>
<div class="divcss5-cent">此DIV右对齐显示</div> 
</body>
</html>

使用多属性实现垂直居中对齐:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>实例</title> 
  <title>php.cn</title>
    <style type="text/css">
    .wrp {
        background-color: #b9b9b9;
        width: 340px;
        height: 260px;
    }
    .box {
        color: white;
        background-color: #3e8e41;
        width: 200px;
        height: 120px;
        overflow: auto;
    }
    .wrp1 { position: relative; }
    .box1 {
        margin: auto;
        position: absolute;
        left: 0; right: 0; top: 0; bottom: 0;
    }
</style>
<body>
<div class="wrp wrp1">
    <div class="box box1">
        <h3>完全居中:</h3>
        <h3>利用css定位规则,设置左右、上下方向定位为0,margin为auto</h3>
    </div>
</div>
</body>
</html>


继续学习
||
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<title>php.cn</title>
<style type="text/css">
.wrp {
background-color: #b9b9b9;
width: 340px;
height: 260px;
}
.box {
color: white;
background-color: #3e8e41;
width: 200px;
height: 120px;
overflow: auto;
}
.wrp1 { position: relative; }
.box1 {
margin: auto;
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
}
</style>
<body>
<div class="wrp wrp1">
<div class="box box1">
<h3></h3>
<h3>css0marginauto</h3>
</div>
</div>
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
提交重置代码
图片放大关闭