您的位置:首页 > Web前端 > CSS

css实现水平垂直居中的几种方法

2017-05-30 18:44 926 查看
先约定初始化的父元素、子元素

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>css实现水平垂直居中的几种方法</title>
<style>
#container{
width: 400px;
height: 400px;
position: relative;
background: #CCC;
margin:0 auto;
}

#box{
width: 200px;
height: 200px;
background: #F00;
position:absolute;
}

</style>
</head>
<body>
<div id="container">
<div id="box">我是一行文字</div>
</div>
</body>
</html>


1、绝对定位居中。

#container{
width: 400px;
height: 400px;
position: relative;
background: #CCCCCC;
margin:0 auto;

overflow:auto;  /*可不加,防止内容溢出 */
}
#box{
width: 200px;
height: 200px;
background: #F00;
position: absolute;

margin: auto;
left: 0;
top: 0;
right: 0;
bottom: 0;

}


2、相对定位绝对定位和负边距。

#container{
width: 400px;
height: 400px;
position: relative;
background: #CCCCCC;
margin: 0 auto;

}
#box{
width: 200px;
height: 200px;
background: #F00;
position: absolute;

left: 50%;
top: 50%;
margin: -100px 0 0 -100px;

}


3、弹性布局,适合宽度高度未知的情况,但是要注意兼容性。

#container{
width: 400px;
height: 400px;
position: relative;
background: #CCCCCC;
margin: 0 auto;

display: flex;
justify-content: center;  /*项目在主轴方向上对齐 */
align-items: center;   /*项目在交叉轴方向上对齐 */
}
#box{
width: 200px;
height: 200px;
background: #F00;
position: absolute;
}


4、css3的transform,适合高度宽度未知的情况。

#container{
width: 400px;
height: 400px;
position: relative;
background: #CCCCCC;
margin: 0 auto;
}
#box{
width: 200px;
height: 200px;
background: #F00;
position: absolute;

left: 50%;
top: 50%;
transform: translate(-50%,-50%);/* 根据自身高宽度位移*/
}


5、分别对父盒子、子盒子使用display:table-cell,inline-block,适合高度宽度未知的情况。

#container{
width: 400px;
height: 400px;
/*position: relative;*/
background: #CCCCCC;
margin: 0 auto;

display: table-cell;
text-align: center;
vertical-align:middle;

}
#box{
width: 200px;
height: 200px;
background: #F00;
/*position: absolute;*/

display: inline-block;

}


6、另外,对于文字或图片而言( inline元素 ):

水平居中:text-align:center;

垂直居中:display:table-cell; vertical-align:middle;

或者,配合line-height;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: