css实现居中的方法有非常多,所以这里不会全部列举。就选择自己比较喜欢的几种居中方式介绍一下。
推荐几篇关于“css居中”的文章供大家深入学习:
三、Centering in CSS:A Complete Guide(国外大牛)
简要介绍一下(详细应用可参考上面的三篇文章)。
水平居中:
方法一:margin:0 auto;//固定宽度
方法二:display:inline-block配合text-align:center;(宽度不用固定)
举例:
body{//父元素
text-align: center;
}
.div1{
display: inline-block;
}
方法三:display:flex;配合justify-content: center;(宽度不用固定)
举例:
body{
display: flex;
justify-content: center;
height: 300px;
background-color: red;
}
<div class="div1" style="height: 300px;background-color: red;">
我是一段无足轻重的文字
</div>
方法四:width: fit-content; 配合margin:0 auto;(宽度不用固定)
举例:
.div1{
width: fit-content;
margin:0 auto;
}
<div class="div1" style="height: 300px;background-color: red;">
我是一段无足轻重的文字
</div>
方法五:定位配合负margin值(固定宽度)
举例:
.div1{
position: relative;/*绝对定位也一样*/
left: 50%;
margin-left: -200px;
}
<div class="div1" style="width:400px;height: 300px;background-color: red;">
我是一段无足轻重的文字
</div>
方法六:浮动配合相对定位(要有一层父元素包裹)
举例:
.div1{
position: relative;
left: -50%;
}
.container{
float: left;
position: relative;
left: 50%;
}
<div class="container">
<div class="div1" style="height: 300px;background-color: red;">
我是一段无足轻重的文字
</div>
</div>
垂直居中:
方法一:绝对定位和负margin值(固定高度)
举例:
.div1{
position: absolute;
top:50%;
margin-top: -150px;
}
<div class="div1" style="width:300px;height: 300px;background-color: red;">
我是一段无足轻重的文字
</div>
方法二:绝对定位+tranlate(其实是方法1的变形:不过不用固定高度)
举例:
.div1{
position: absolute;
top:50%;
transform: translate(0,-50%);
}
<div class="div1" style="width:20px;background-color: red;">
我是一段无足轻重的文字
</div>
方法三:绝对定位+0+margin:auto(固定宽度)
举例:
div1{
position: absolute;
top:0;
bottom:0;
margin:auto;
}
<div class="div1" style="width:300px;height: 300px;background-color: red;">
我是一段无足轻重的文字
</div>
方法四:display:flex配合align-items:center;(写父元素上,注意body上面无效,不用固定高度)
举例:
.fa{
display: flex;
align-items: center;
}
<div class="fa" style="width:500px;height:500px;background-color: blue;">
<div class="div1" style="width:200px;height:200px;background-color: red;">
我是一段无足轻重的文字
</div>
</div>
水平垂直居中就不做总结了,合适的综合水平居中和垂直居中即可。