本文参照此文章 元素居中的多种方法——css布局技巧,做个笔记,以便后用查询,如有侵权,联系删除
题目:元素布局,让 box
在 content
上下左右居中
<div class="content">
<div class="box"></div>
</div>
1. 元素定位 position:absolute
.content{
width:500px;
height:300px;
border:1px solid #0a3b98;
position: relative;
}
.box{
width:100px;
height:40px;
background: #f0a238;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}
2. CSS3
位移 translate(x, y)
.content{
width:500px;
height:300px;
border:1px solid #0a3b98;
position: relative;
}
.box{
width:100px;
height:40px;
background: #f0a238;
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
3. 利用内联块元素 display:inline-block
.content{
width:500px;
height:300px;
border:1px solid #0a3b98;
text-align: center;
}
.content:before{
content: '';
height:100%;
width:0;
display: inline-block;
vertical-align: middle;
// vartical-align 这个属性只对内联元素以及内联块元素起作用
// 这个属性有一个缺点:需要一个参照物,也就是说如果父级里面有两个子元素
// 两个子元素都设置了vertical-align:middle,那么得到的效果只是这两个元素之间居中对齐而已
}
.box{
width:100px;
height:40px;
background: #f0a238;
display: inline-block;
vertical-align: middle;
}
4. 弹性盒模型
.content{
width:500px;
height:300px;
border:1px solid #0a3b98;
display: flex;
justify-content: center;
align-items: center;
}
.box{
width:100px;
height:40px;
background: #f0a238;
}
5. 网格布局 Grid
.content{
width:500px;
height:300px;
border:1px solid #0a3b98;
display: grid;
justify-content: center;
align-items: center;
}
.box{
width:100px;
height:40px;
background: #f0a238;
}