CSS垂直居中的方法

水平居中的方法很简单,通常都是一个margin:0 auto搞定,但是垂直居中就没有那么简单了。首先来说说垂直居中的几种情况。

1、文字垂直居中

文字垂直居中的方法一般是设置高度与行高一致,然后文字就垂直居中了。来看下面的示例:

<html>
<head>
<meta charset="gb2312" />
<title>高度自适应布局</title>
<style>
    p{
        height:100px;
        background-color:#dcdcdc;
        color:#333;
    }
</style>
</head>
<body>
    <div>
        <p style="line-height:100px;">    
            这是一行文字    
        </p>
    </div>
</body>
</html>

其显示效果如下:

2、将一个div垂直居中
下面来将一个div设置到整个浏览器的中间,要设置到浏览器的中间,所以我们就要求页面要占满整个浏览器,所以从html、body要逐层设置其高度为100%。

<html>
<head>
<meta charset="gb2312" />
<title>高度自适应布局</title>

<style>
html, body{
    height: 100%;
}

    div{
        width:200px;
        height:200px;
        background-color:#dcdcdc;

        position: relative; 
        top: 50%; /* 向下偏移50% */
        transform: translateY(-50%);    /* 再向上偏移50% */
    }
</style>

</head>
<body>
    <div>
    </div>
</body>
</html>

其效果如下所示:

3、CSS3新属性设置居中
如果是CSS3,则可以设置外层的display为flex,然后align-items为center,justify-content为center也可以实现垂直居中的效果。

<html>
<head>
<meta charset="gb2312" />
<title>高度自适应布局</title>

<style>
html, body{
    height: 100%;
}

body{
    display: flex;
    align-items: center; /*定义body的元素垂直居中*/
    justify-content: center; /*定义body的里的元素水平居中*/
}

div{
    width:200px;
    height:200px;
    background-color:#dcdcdc;
}
</style>

</head>
<body>
    <div>
        
    </div>
</body>
</html>

效果如下所示:

4、绝对定位实现居中
还有一种可以应用绝对定位实现居中的,我们都知道绝对定位是根据其最近relative、absolute父元素来定位的,使用这种方式,我们根本都不需要设置那么多的height:100%,只需要将其父元素设置成relative就可以了,想它相对于那个元素居中就相对于哪个元素居中。来看示例:

<html>
<head>
<meta charset="gb2312" />
<title>高度自适应布局</title>

<style>
.div_outer{
    width:400px;
    height:400px;
    border:1px solid blue;
    position:relative;
}
.center_middle{
    width:200px;
    height:200px;
    background-color:#dcdcdc;    

    margin: auto;  
    position: absolute;  
    top: 0; left: 0; bottom: 0; right: 0;  
}
</style>

</head>
<body>
    <div class="div_outer">
        <div class="center_middle">
            
        </div>
    </div>
</body>
</html>

其效果如下:

 

来源文章:

http://blog.csdn.net/freshlover/article/details/11579669

http://www.cnblogs.com/yugege/p/5246652.html

posted on 2017-02-13 16:39  逆心 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/kissdodog/p/6394149.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值