css/css3实现水平垂直居中

2018-03-17  本文已影响0人  张鸽

水平居中:

垂直居中:

#div{
    top: 50%;
    margin-top: -50px;  /* margin-top值为自身高度的一半 */
    position: absolute;
    padding:0;
}

水平垂直居中

<div id="div1">
    <p>水平垂直居中</p>
</div>
<style>
        #div1{
            width:200px;
            height: 200px;
            position: absolute;
            left:50%;
            top:50%;
            margin-top: -100px;
            margin-left: -100px;
            background-color: antiquewhite;
            text-align: center;
        }
</style>
<div id="div1">
    <p>水平垂直居中</p>
</div>
 <style>
        #div1{
            width:200px;
            height: 200px;
            position: absolute;
            margin: auto;
            left:0;
            right:0;
            top:0;
            bottom:0;
            text-align: center;
            background-color: antiquewhite;
        }
    </style>
<div id="div1">
    <p>水平垂直居中</p>
</div>
    <style>
        #div1{
            position: absolute;
            left: 50%;
            top:50%;
            transform: translate(-50%,-50%);//使用css3的transform属性
        }
    </style>
<div id="div1">
    <p>水平垂直居中</p>
</div>
<style>
        #div1{
            display: flex;                //使用flex布局
            justify-content: center;      //子元素水平居中
            align-items: center;          //子元素垂直居中
            height: 400px;                //设置高度来查看垂直居中效果
            background-color: antiquewhite;
            }
</style>

git地址:https://github.com/zhangge1998/-centering-control

上一篇 下一篇

猜你喜欢

热点阅读