css居中对齐的几种方法
css居中对齐的几种方法
css居中对齐的几种方法
- 弹性盒子
- position:absolute
- fixed+margin:auto
- 弹性盒子与其他传统的对比:
弹性盒子
设置弹性容器的
主轴对齐属性:justify-content:center
交叉轴的对其属性:align-items:center
.perent{position: absolute;display: flex;display: -webkit-flex;width: 500px;height:500px;justify-content: center;align-items: center;background: green;flex-direction: row-reverse; flex-wrap: wrap;justify-content: center;align-items: center;}.left,.right{flex:1 1 200px;width: 100px;height: 100px;background: red;}.middle{flex-grow: 1;height: 100px;background: blue;}
position:absolute
设置父元素position:absolute或者relative;
设置该元素:position:absolute;
left:50%;
right:50%;
margin-left:-该元素的边长0.5倍
margin-top:-该元素的边长0.5倍
.con{position: absolute;width: 200px;height: 200px;bottom: 0;background: green;}.middle{width: 100px;height: 100px;background: blue;position: absolute;left:50%;top:50%;margin-left: -50px;margin-top: -50px; }
fixed+margin:auto
设置要对齐的元素的
position:fixed;
left:0;
right:0;
top:0;
bottom: 0;
margin: auto;
.middle{/*flex-grow: 1;*/width: 100px;height: 100px;background: blue;position: fixed;left:0;right:0;top:0;bottom: 0;margin: auto;}
弹性盒子与其他传统的对比:
引入弹性盒布局模型的目的是提供一种更加有效的方式来对一个容器中的子元素进行排列、对齐和分配空白空间。