css技巧|实现元素水平和垂直同时居中的四种方法
在前端界面CSS布局中,实现元素的水平和垂直同时居中的方法是经常会用到的技巧。这个技巧其实不难,但许多初学前端的朋友还不是很懂,这里给初学前端的朋友介绍下元素水平和垂直同时居中的四种方法。
1. margin或padding配合调整
由俭入奢,第一种方法是最基础也是比较局限的,就是用margin和padding配合调整,按已知的大小去控制间距:
1 | .parent { width: 200px; height: 200px; background-color: #ADD8E6; padding: 50px 0; /* (200-100)/2 上下各50px*/ box-sizing: border-box; } .son { width: 100px; height: 100px; background-color: #DB7093; margin: 0 auto; /*水平居中*/ } |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
12 | |
13 |
2. 定位调整
升级一下,用定位解决。父元素relative相对定位,子元素absolute绝对定位,上左各50%,再用margin-top、margin-left负值调整。
1 | .parent { width: 200px; height: 200px; background-color: #ADD8E6; position: relative; /*相对定位*/ } .son { width: 100px; height: 100px; background-color: #DB7093; position: absolute; /*绝对定位*/ top: 50%; left: 50%; margin-top: -50px; /*返回一半的高度*/ margin-left: -50px; /*返回一半的宽度*/ } |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
12 | |
13 | |
14 | |
15 | |
16 |
3. css3动画调整
这个方法跟上一个雷同,优点在于代码量少一行和不需要计算数值。同样的,父元素relative相对定位,子元素absolute绝对定位,上左各50%,然后用css3的translate(-50%, -50%)在x、y轴上各返回本身的一半位移。
1 | .parent { width: 200px; height: 200px; background-color: #ADD8E6; position: relative; /*相对定位*/ } .son { width: 100px; height: 100px; background-color: #DB7093; position: absolute; /*绝对定位*/ top: 50%; left: 50%; transform: translate(-50%, -50%); /*x、y轴返回元素一半的位移*/ } |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
12 | |
13 | |
14 | |
15 |
4. flex弹性布局调整
最后一种方法个人觉得是较高级的写法。html5提供了广受开发者喜爱的flex弹性布局属性,功能十分强大实用。要实现元素水平垂直居中,只要父元素设置弹性布局,用justify-content和align-items属性调整主轴、副轴上居中。
1 | .parent { width: 200px; height: 200px; background-color: #ADD8E6; display: flex; /*弹性布局*/ justify-content: center; /*子元素水平居中*/ align-items: center; /*子元素垂直居中*/ } .son { width: 100px; height: 100px; background-color: #DB7093; } |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
12 | |
13 |
以上就是前端CSS布局中实现元素的水平和垂直同时居中的技巧,同学们多多练习,就能掌握啦!