盒子的居中问题

居中:分位水平居中和水平垂直居中。

1.水平居中

  • 使用外边距水平居中:

margin:0 auto;

  • 如果内部元素为inline-block;则只需设置其父元素的text-align:center;

2.水平垂直居中

  • 使用定位水平垂直居中:
  • position:absolute;left:50%;top:50%;margin-left:-1/2*height ;margin-top:-1/2*width;
  • position:absolute; left:50%;top:50%;transform:translate(-50%,-50%); 
 1 定义两个盒子------wrapper和 .header
 2 .wrapper{
 3     background: pink;
 4     width:100px;
 5     height:200px;
 6     position:relative;
 7 }
 8 .header{
 9     background:red;
10     width:50px;
11     height:50px;
12     position:absolute;
13     left:50%;
14     top:50%;
15     transform:translate(-50%,-50%);
16 
17 }

····················

  • margin和定位组合使用:
.wrapper{
    background: pink;
    width:100px;
    height:200px;
    position:relative;
}
.header{
    background:red;
    width:50px;
    height:50px;
    position:absolute;
    left:0;
    top:0;
    right:0;
    bottom: 0;
    margin: auto;

}
原文地址:https://www.cnblogs.com/alaner/p/9564576.html