css实现垂直水平居中

方法一、用before伪元素、inline-block、vertical-align实现

该方法适用于居中内容高度未知的情况

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .wrap{
            text-align:center;
            background:green;
            height:200px;
        }
        .wrap:before{
            content:'';
            vertical-align:middle;
            display:inline-block;
            height:100%;
        }
        .content{
            width:400px;
            border:1px solid #ccc;
            display:inline-block;
            vertical-align:middle;
        }
    </style>
</head>
<body>
<div class="wrap">
    <div class="content">
        css设置内容垂直水平居中
    </div>
</div>
</body>

效果图

方法二、用相对绝对定位和负边距实现上下左右居中

该方法适用于内容高度宽度已知的情况

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .wrap{
            text-align:center;
            background:green;
            height:500px;
            position:absolute;
        }
        .content{
            width:400px;
            height:200px;
            top:50%;
            left:50%;
            position:relative;
            border:1px solid #ccc;
            margin: -100px 0 0 -200px;
        }
    </style>
</head>
<body>
<div class="wrap">
    <div class="content">
        css设置内容垂直水平居中
    </div>
</div>
</body>

利用相对定位设置top和left为50%使content左上角位于wrap中心,再利用负边距使content居中,上边距为负的content高度的一半,右边距为负的content宽度的一半  

效果图

 

方法三、用绝对定位来实现居中

适合高度、宽度已知的情况

.wrap{
            background:green;
            text-align: center;
            height: 400px;
            background: #4dc71f;
            position: relative;
        }
        .content{
            position: absolute;
            margin: auto;
            top: 0;
            right: 0;
            left:0;
            bottom: 0;
            width:400px;
            height:200px;

            border:1px solid #ccc;
        }

  效果图

方法四、用table-cell和inline-block实现水平垂直居中

 

.wrap{
    background:green;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    height: 300px;
}
 .content{
    display: inline-block;
    border:1px solid #ccc;
}

方法五、用css3中的transform实现水平垂直居中

.wrap{
    background:green;
    position:relative;
    height: 300px;
}
.content{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    border:1px solid #ccc;
}

  效果图

方法六、flexbox实现水平垂直居中

.wrap{
    background:green;
    display:flex;
    justify-content:center;
    align-items:center;
    height: 300px;
}
.content{
    border:1px solid #ccc;
}

效果图

 

转载于:https://www.cnblogs.com/lhyhappy365/p/6440600.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值