fit-content的兼容性:2023年3月9日看来,在较新的主流浏览器兼容性还可以。
fit-content 属性可以用于设置元素的 width、height、min-width、min-height、max-width 和max-height,此时最大和最小尺寸将基于元素的实际内容尺寸计算。
常用于包裹英文的元素,使其内容不被截断。
由于fit-content会根据实际的内容长度进行具体计算,所以也适用于不定尺寸元素在渲染时的尺寸确定。实际确定的长度便于居中定位。
<style>
.b {
position: relative;
width: 300px;
height: 200px;
border: #949494 1px solid;
}
.i {
position: absolute; //必须开启定位
width: fit-content;
height: fit-content;
border: #ffffff 1px solid;
margin: auto;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}
</style>
<div class="b">
<div class="i">text</div>
</div>
效果:
若内部是块元素,不开启定位同样可以水平居中,但是垂直方向上位于顶部。
原理:
总所周知,盒模型垂直方向由top+margin-top+boder-top+padding-top+height+padding-bottom+border-bottom+margin-bottom+bottom确定。
当margin:auto时,水平方向上由于内容相对固定,浏览器会计算水平左右的距离,实现水平方向的居中。但是垂直方向上由于太多不确定的值,所以单独设置margin:auto和margin: 0 auto效果类似。垂直方向上位于顶端。
而开始定位后,尤其top与bottom设定具体值后,height也有具体值,此时浏览器就会计算margin-top和margin-bottom的值,从而实现垂直方向居中。
关于magin取值为auto时: