C军

不玩博客了!

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

水平居中的方法很简单,通常都是一个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  逆心  阅读(902)  评论(0编辑  收藏  举报