最近一个刚刚毕业的朋友说,他面试时候,遇到最频繁的css问题就是垂直居中,这里给出几种垂直居中方式!


<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	
</head>
<style>
	html {
    background: #f9f9f9;
    overflow-y: scroll;
}
body{
	font-size: 14px;
	font-family: "微软雅黑";
	padding: 0;
	margin:0 auto;
}

#child {
	position:absolute;
	top:50%;
	left: 50%;
	width: 100px;
	height:20px;
	margin:-10px 0px 0px -50px; /* negative half of the height */
    background-color: #ddd;
    text-align: center;
    line-height:20px;
}
</style>
<body>
<div id="parent">
		<div id="child">Content here</div>
</div>
</body>
</html>

  

<!DOCTYPE html>
    <head>
        <title>center</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <style>    
            .root {
                width:100%;
                height:100%;
                display:table;
                background-color: rgba(0,0,0,0.5);
                position: fixed;
            }
            .parent {
                display:table-cell;
                vertical-align:middle;
            } 
            .child {
                width:50px;
                height:50px;
                background:#22B14C;
                margin:0 auto;
            }            
        </style>
    </head>
    <body>
        <div class="root">
            <div class="parent">
                 <div class="child"></div>
            </div>
        </div>
    </body>
</html>

  

<!DOCTYPE html>
    <head>
        <title>center</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <style> 
        body{
            margin:0;
            padding: 0;

        }   
            .parent {
                width:100%;
                height:100%;
                border:1px solid black;
                position: fixed;
                background-color: rgba(0,0,0,0.5);
           
            }
            .child {
                position:absolute;
                width:50px;
                height:50px;
                top:50%;
                left:50%;
       
                -webkit-transform: translate(-50%,-50%);
                    -ms-transform: translate(-50%,-50%);
                   -o-transform: translate(-50%,-50%);
                   transform: translate(-50%,-50%);
                background:#22B14C;
            }         
        </style>
    </head>
    <body>
        <div class="parent">
            <div class="child">
                 
            </div>
            
        </div>
    </body>
</html>

  


 


posted @ 2016-04-25 08:47  八bug哥哥  阅读(248)  评论(0编辑  收藏  举报