码迷,mamicode.com
首页 > Web开发 > 详细

CSS垂直居中

时间:2015-10-31 12:45:38      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

1.单行内容居中

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Test</title>
	<style type="text/css">
	#wrapper{
		background: #ddd;
		height: 40px;
		line-height: 40px;
		width: 200px;
		text-align: center;
	}
	</style>
</head>
<body>
<div id="wrapper">
	<span>span</span>
</div>
</body>
</html>

主要是height和line-height高度一致

2.让未知内容高度的元素居中

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Demo</title>
    <style type="text/css">
        #outer{
            width:500px;
            height:200px;
            margin: 50px auto;
            border:1px solid #CCC;
            display:table;
            text-align:center;
            #position:relative;
        }
        #middle{
            display:table-cell;
            vertical-align:middle;
            #position:absolute;
            #top:50%;
            #left:50%;
        }
        #inner{
            #position:relative;
            #top:-50%;
            #left:-50%;
        }
    </style>
</head>
<body>
    <div id="outer">
        <div id="middle">
            <img id="inner" src="http://static.cnblogs.com/images/logo_small.gif"/>
        </div>
    </div>
</body>
</html>

主要原理是标准浏览器下用table和table-cell布局,然后用vertical-align:middle居中元素,但IE67不支持table布局,所以用了用了css hake,就是带#开头的属性。

3.让已知内容高度的元素居中

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Demo</title>
    <style type="text/css">
        #outer{
            width:500px;
            height:200px;
            margin: 50px auto;
            border:1px solid #CCC;
            position:relative;
        }
        #inner{
            position:relative;
            left:50%;
            top:50%;
            margin-left:-71px;
            margin-top:-27px;
        }
    </style>
</head>
<body>
    <div id="outer">
            <img id="inner" src="http://static.cnblogs.com/images/logo_small.gif"/>
    </div>
</body>
</html>

用负margin实现,但是要知道居中内容的宽度和高度。

转自: http://www.cnblogs.com/jscode/archive/2012/09/23/2698809.html

CSS垂直居中

标签:

原文地址:http://www.cnblogs.com/erduyang/p/4925158.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!