css实现元素水平居中和垂直居中的方法

水平居中

水平居中的方法大家应该都知道

1.在父元素的里面加

/父元素
{
    text-align:center;
}
//子元素
{
    //如果不管是就在子元素加
    display:inline/inline-block;
}

2.前提:居中的元素必须是块级元素


//子元素
{
    margin: 0 auto;
    //如果不管是就在子元素加
    display:inline/inline-block;
}

垂直居中

1.绝对定位(一)

//已知宽高
//父元素
{
    position: relative;
    width:宽;
    height: 高;
}
//子元素
{
    width: 宽;
    height: 高;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -宽/2;
    margin-top: -高/2;
}

2.绝对定位(二)

//已知宽高
//父元素
{
    position: relative;
    width: 250px;
    height: 250px;
    background: blue;
}
//子元素
{
    position: absolute;
    width: 50px;
    height: 50px;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background: red;
}

3.绝对定位(三)

//已知宽高
//父元素
{
    position: relative;
    width: 250px;
    height: 250px;
    background: blue;
}
//子元素
{
    position: absolute;
    width: 50px;
    height: 50px;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: red;
}

4.弹性布局

//父元素
{
    display: flex;
    flex-direction: row;
    justify-content: center;/*水平居中*/
    align-items: center;/*垂直居中*/
}

5.使用table-cell进行居中显示

//已知宽高
//父元素
{
    display: table-cell;
    vertical-align: middle;
    width: 250px;
    height: 250px;
    background: blue;
}
//子元素
{
    width: 70px;
    height: 50px;
    margin: 0 auto;
    background: red;
}
发布了32 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Jadeyqc/article/details/104806004