relative 和 absolute 实现居中

父元素 

.father{
    position: relative;
    width: 400px;
    height: 400px;
    background: blue;
    /*在此处添加相应代码*/
}

子元素

.child{
    position: absolute;
    width: 100px;
    height: 100px;
    .lrtb();
    background: red;
}

情况1:子元素水平居中,.lrtb设置左右为0,margin : 0 atuo;

.lrtb(){
  left: 0;
  right: 0;
  margin: 0 auto;
}

情况2 :子元素垂直居中 .lrtb 设置上下位0 ,margin : auto 0 ;

.lrtb(){
  top:0;
  bottom: 0;
  margin: auto 0;
}

情况3: 子元素垂直水平居中,结合情况1,2,margin : auto

.lrtb(){
  left: 0;
  right: 0;
  top:0;
  bottom: 0;
  margin: auto;
}
注意!要使居中生效,子元素必须要设置高或宽

猜你喜欢

转载自blog.csdn.net/masorl/article/details/80700964
今日推荐