CSS实现水平垂直居中在实际应用中非常常见的,实现方法有好几种,在此特别总结一下
方法一:margin: auto;实现绝对定位元素的居中
<body>
<div class="content"></div>
</body>
<style>
.content{
width: 200px;
height: 200px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
background-color:green;
}
</style>
关键点:绝对定位 上下左右均为0 margin为auto
方法二 绝对定位元素的居中实现
<body>
<div class="content"></div>
</body>
<style>
.content{
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
/* margin-top: -100px; */
/* margin-left: -100px; */
/* css3中,transform 中 translate 偏移的百分比是相对于自身大小而说的,但兼容性不好 */
transform: translate(-50%, -50%);
background-color:red;
}
关键点:当不知道元素本身大小时候,css3提供了transform: translate(-50%, -50%)来实现居中效果。
方法三 CSS3.0弹性布局
<body>
<div class="content"></div>
</body>
<style>
html,body{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body{
display: flex;
align-items: center;/*定义body的元素垂直居中*/
justify-content: center;/*定义body的元素水平居中*/
}
.content{
width: 100px;
height: 100px;
background: red;
}
</style>
方法四 相对定位
<style>
html,body{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.content{
width: 300px;
height: 300px;
background: orange;
margin: 0 auto;/*水平居中*/
position: relative;/*设置position*/
top: 50%; /*偏移*/
/*margin-top: -150px;*/ /*第一种:margin-top*/
transform: translateY(-50%);/*第二种:transform:转换*/
}
</style>