亮闪闪的效果图

居中效果图
如何垂直居中一个属性为item的div元素?
<div class="box"> <div class="item"></div></div>
1、方法一
已知子元素宽高,父元素随意;
设置父元素:定位为relative;
设置子元素:
定位为absolute,
left为50%,top为50%,
margin-left为负的子元素宽度的一半,
margin-top为负的子元素高度的一半;
.box { position: relative; width: 500px; height: 500px; background-color: yellow; }.item { position: absolute; width: 100px; height: 100px; left: 50%; top: 50%; background-color: blue; margin-left: -50px; margin-top: -50px; }
2、方法二
已知父元素宽高及子元素宽高;
设置父元素:
定位为relative,
margin为auto;
设置子元素:
定位为absolute,
margin-left为(父元素宽 - 子元素宽)/ 2,
margin-top为(父元素高 - 子元素高)/ 2;
.box { position: relative; width: 500px; height: 500px; background-color: yellow; margin: auto; }.item { position: absolute; margin-left: 200px; margin-top: 200px; width: 100px; height: 100px; background-color: blue; }
3、方法三
设置父元素:
display为table-cell,
垂直对齐方式vertical-align: middle,
文本水平对齐方式text-align: center;
设置子元素:为块级元素均匀分布display: inline-block;
.box { display: table-cell; vertical-align: middle; text-align: center; width: 500px; height: 500px; background-color: yellow; }.item { display: inline-block; width: 100px; height: 100px; background-color: blue; }
4、方法四
设置父元素:
display为flex,
水平居中justify-content: center,
垂直居中align-items:center;
.box { display: flex; justify-content: center; align-items:center; width: 500px; height: 500px; background-color: yellow; }.item { width: 100px; height: 100px; background-color: blue; }
文章转载于:https://www.jianshu.com/p/9ce2645869de
原著是一个有趣的人,若有侵权,请通知删除
还没有人抢沙发呢~