css实现div水平垂直居中--2016.08.02

水平居中最简单的就是设置元素margin:0 auto;

下面介绍4种使div垂直居中的方法:

1.通过display:table和display:table-cell实现

html代码:

css代码:

#wrap{
    display:table;
}
#cell{
    display:table-cell;
    vertical-align:middle;
}
#center{
    margin:0 auto;
}

优点:不需给出center的宽和高,且当center的高度超过wrap时center的内容不会被截断。

2.通过transform:translate(-50%,-50%)实现

html:代码

css代码:

#wrap{
    position:relative;
}
#center{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}

优点:不需要给出center的宽高
缺点:center的高度超过wrap时center的内容会被截断

3.利用margin:auto和position:absolite实现

html:代码

css代码:

#wrap{
    position:relative;
}
#center{
    position:absolute;
    width:400px;
    height:400px;
    top:0;
    left:0;
    right:0;
    bottom:0;
    margin:auto;
}

缺点:需要给出宽高;
center的高度超过wrap时center的内容会被截断

4.负margin实现

html:代码

css代码:

#wrap{
    position:relative;
}
#center{
    position:absolute;
    width:400px;
    height:400px;
    top:50%;
    left:50%;
    margin-left:-200px;
    margin-top:-200px;
}

缺点:需要给出宽高;
center的高度超过wrap时center的内容会被截断

你可能感兴趣的:(css实现div水平垂直居中--2016.08.02)