前端中的居中问题

2019-01-13  本文已影响0人  IvyAutumn

一、文本居中

二、子盒子在父盒子里实现水平居中

1.margin:0 auto

块级元素相对于页面居中。
该盒子需设置了width,不然其width默认为:auto,此时会把值为auto的margin的值改为0

2.子元素使用绝对定位方式, 以及负值的margin-left

.parent{
  position:relative;
}
.child{
  position:absolute
  width: 固定;
  left:50%
  margin-left: -0.5*宽度;
}

3.子元素使用绝对定位方式, 以及left:0;right:0;margin:0 auto

.parent{
  position:relative;
}
.child{
    position: absolute;
    width: 100px;
    height: 100px;
    left: 0;
    right: 0;
    margin: 0 auto;
    background: red;
}

4.使用flex

在父容器中设置flex属性

.parent{
  display:flex
  justify-content: center
}

使用CSS3中新增的transform属性

        .box{
            width: 200px;
            height: 200px;
            background: pink;
            position: relative;
        }
        .child{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 50%;
            transform: translate(-50%,0);
        }

三、子盒子在父盒子里实现居中

image.png

1.子元素使用绝对定位方式, 以及负值的margin-left,margin-top

.parent{
  position:relative;
}
.child{
  position:absolute
  width: 固定;
  height:固定;
  left:50%;
  top:50%;
  margin-left: -0.5*宽度;
  margin-top: -0.5*高度;
}

2.子元素使用绝对定位方式, 以及left:0;right:0;top:0;bottom:0;margin: auto

.parent{
  position:relative;
}
.child{
    position: absolute;
    width: 100px;
    height: 100px;
    left: 0;
    right: 0;
        top:0;
        bottom:0;
    margin: auto;
    background: red;
}

3.使用flex布局

        .box{
            width: 200px;
            height: 200px;
            background: pink;
            display: flex;
            justify-content: center; //水平居中
                       align-items: center; //垂直居中
        }
        .child{
            width: 100px;
            height: 100px;
            background: red;
        }

4.使用CSS3中新增的transform属性

        .box{
            width: 200px;
            height: 200px;
            background: pink;
            position: relative;
        }
        .child{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
                        top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }
上一篇 下一篇

猜你喜欢

热点阅读