CSS 水平垂直居中方式
文章目录
1.绝对定位 absolute 负margin
思路:使用绝对定位,负边距,需要知道子元素的宽高,且把子元素设置为position:absolute
,再设置left和top为50%,再加上负边距,margin-left和margin-top
相对于宽高各一半
<style>
.box {
background: red;
width: 100px;
height: 100px;
position:absolute;
top:50%;
left:50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
1.优点
- 易于理解,兼容性好
2.缺点
- 需要知道子元素的宽高
2.绝对定位 absolute margin:auto
思路:使用绝对定位方式,left:0;right:0;top:0;botton:0;margin:auto
.box{
background: red;
width: 100px;
height: 300px;
position: absolute;
left:0;
right:0;
top:0;
bottom: 0;
margin: auto;
}
1.优点
- 易于理解,兼容性好
2.缺点
- 需要知道子元素的宽高
3.绝对定位 absolute calc
思路:与第一种方式其实也差不多,不过这里使用的是calc计算函数
.box {
background: red;
width: 100px;
height: 100px;
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
1.优点
- 易于理解,兼容性依赖calc
2.缺点
- 需要知道子元素的宽高
4.绝对定位 absolute transform
思路:利用CSS3的transform方法,与第一种方法也类似,但是IE8以下不支持
.box {
background: red;
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
1.优点
- 易于理解,兼容性依赖transform
- 不需要知道子元素的宽高
2.缺点
- 如果同时使用transform的其他属性,会产生一些影响
5.flex布局
思路:弹性盒布局,只需要将父元素设置三个属性即可:display:flex;justify-content:center;align-item:center
.box {
display: flex;
justify-content: center;
align-items: center;
width: 600px;
height: 600px;
border:1px solid green;
}
.in {
background: red;
width: 100px;
height: 100px;
}
1.优点
简单,快捷
2.缺点
低版本浏览器不支持(IE9以下不支持),不过目前很少用低版本了
6.table表格
思路:利用css新增的table属性,把普通元素变为table元素
.box {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 600px;
height: 600px;
border:1px solid green;
}
.in {
display: inline-block;
background: red;
width: 100px;
height: 100px;
}
yle>
7.grid布局
思路:grid布局跟flex也差不多的
1.父元素指定子元素对齐方式:
.box {
display: grid;
justify-content: center;
align-items: center;
width: 600px;
height: 600px;
border:1px solid green;
}
.in {
background: red;
width: 100px;
height: 100px;
}
2.子元素指定自己的对齐方式:
.box{
display: grid;
width: 300px;
height: 300px;
background: red;
}
.in{
background: yellow;
width: 100px;
height: 100px;
align-self: center;
justify-self: center;
}
8.空元素span
思路:利用空标签span设置它的vertical-align基准线为中间,并且设置为inline-block
,宽度为0
这种方式不好的地方就是多了一个没有用的空标签
.box {
width: 600px;
height: 600px;
text-align: center;
border:1px solid green;
}
.base-line{
width: 0;
height: 100%;
vertical-align: middle;
display: inline-block;
}
.in {
display: inline-block;
background: red;
width: 100px;
height: 100px;
}
<div class="box">
<div class="in">
</div>
<span class="base-line"></span>
</div>
9.总结
推荐使用第1,2,3,4,5这几种方式,然后绝对定位方式适合大范围的,比如弹框居中.如果是局部的话,建议使用弹性盒