在我们日常开发的时候,经常会使用到css 的居中布局,不论是移动端还是我们的pc端,今天总结归纳几种css居中布局的方法,代码可以自己修改 ,为了演示,所以自己加 了宽高,有错误欢迎大家指正。
1: 水平居中方法 :
主要知识点:父级元素parent设置 text-align: center;
子元素child设置 display: inline-block;
如图:
shuip.png
css代码一
.parent{ text-align: center; width: 500px; height: 500px; margin: 10px auto; background: #ccc; }.parent .child{ display: inline-block; padding: 10px; background: pink; }
css代码二:
.parent{ background: #ccc; width: 600px; height: 600px; margin: 20px auto; position: relative; }.parent .child{ position: absolute; left: 50%; background: pink; padding: 10px; transform:translateX(-50%); }
html代码:
<div class="parent"> <div class="child"> 我是垂直居中显示 </div> </div>
2:垂直居中方法:
如图:
2.png
css代码一:
.parent{ display: table-cell; vertical-align: middle; width: 500px; height: 600px; background: #ccc; }.parent .child{ background: pink; padding: 10px; width: 100px; }
html代码:
<div class="parent"> <div class="child"> 我是垂直居中显示 </div> </div>
3:垂直水平都居中:
如图:
5.png
css代码一:
.parent{ text-align: center; background: #ccc; height: 600px; width: 600px; display: table-cell; vertical-align: middle; }.parent .child{ display: inline-block; background: pink; padding: 10px; width: 150px; height: 150px; }
css代码二:
.parent{ background: #ccc; height:400px; width: 400px; position: relative; } .child{ background: pink; padding: 10px; width: 150px; height: 150px; position: absolute; left: 50%; top:50%; transform: translate(-50%,-50%); }
css代码最终版本
.parent{ display: flex; justify-content: center; align-items: center; background: #ccc; height:600px; width: 400px; } .child{ background: pink; padding: 10px; width: 150px; height: 150px; }
html代码
<div class="parent"> <div class="child"> 我是垂直居中和水平居中显示 父级大小,子集大小 ,不固定可以随意更改大小 </div> </div>