如何让子元素在父元素中水平垂直居中七种方法
html:
green
第一种:定位+margin:auto
.container {
position: relative;
width: 300px;
height: 300px;
background: yellow;
}
.box {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background: red;
}
注意:兼容性较好,缺点:不支持IE7以下的浏览器
第二种:定位+margin-left+margin-top
.container {
position: relative;
width: 300px;
height: 300px;
background: yellow;
}
.box {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
width: 100px;
height: 100px;
background: red;
}
注意:兼容性好; 缺点:必须知道元素的宽高
第三种:定位+transfrom
.container {
position: relative;
width: 300px;
height: 300px;
background: yellow;
}
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: 100px;
height: 100px;
background: red;
}
注意:这是css3里的样式; 缺点:兼容性不好,只支持IE9+的浏览器
第四种:弹性盒子
.container {
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height: 300px;
background: yellow;
}
.box {
width: 100px;
height: 100px;
background: red;
}
移动端首选
第五种:flex+margin: auto
.container {
display: flex;
width: 300px;
height: 300px;
background: yellow;
}
.box {
margin: auto;
width: 100px;
height: 100px;
background: red;
}
移动端首选
第六种:形成table-cell,子元素设置display:inline-block
.container {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 300px;
height: 300px;
background: yellow;
}
.box {
display: inline-block;
width: 100px;
height: 100px;
background: red;
}
注意:兼容性:由于display:table-cell的原因,IE6\7不兼容
第七种:line-height+display:inline
.container {
width: 300px;
height: 300px;
line-height: 300px;
text-align: center;
background: yellow;
}
.box {
display: inline;
background: red;
}
【如何让子元素在父元素中水平垂直居中七种方法】职场小白south Joe,望各位大神批评指正,祝大家学习愉快!
推荐阅读
- 2018年11月19日|2018年11月19日 星期一 亲子日记第144篇
- 遇到一哭二闹三打滚的孩子,怎么办┃山伯教育
- 这辈子我们都不要再联系了
- 考研英语阅读终极解决方案——阅读理解如何巧拿高分
- 2019年12月24日
- Ⅴ爱阅读,亲子互动——打卡第178天
- 眼观耳听美食的日子
- 子龙老师语录
- 如何寻找情感问答App的分析切入点
- 成交的种子咖啡冥想