HTML + CSS 连载 | 52 - 绝对定位元素的特点(下)一、将 position 设置为 absolute/f
一、将 position 设置为 absolute/fixed 元素的特点(下)
上篇文章中我们通过绝对定位元素的参照对象的宽度公式实现了元素的居中,根据绝对定位元素的参照对象的高度公式也可以实现元素的垂直居中。
- 定位参照对象的高度 =
绝对定位元素的实际占用高度(自身的高度 height)
+top
+bottom
+margin-top
+margin-bottom
定位元素垂直居中
继续在上一节内容中的页面中操作,添加如下 CSS 代码:
.box .container {
width: 200px;
height: 100px;
background-color: #0f0;
margin: auto 0;
/* width: 100%; */
position: absolute;
/* left: 0;
right: 0;*/
top: 0;
bottom: 0;
}
刷新浏览器,效果如下:
绿色盒子实现了垂直居中,那么根据前面的公式,此时公式中具体的值为:
300 = 100 + 0 + 0 + auto + auo
margin-top
和 margin-bottom
为 auto
,浏览器会为它们分配 100px 来实现这个公式,此时就实现了垂直居中,用绝对定位是可以让一个元素垂直居中的。
如果想要设置完全居中既水平居中且垂直居中就可以设置 margin: auto;
,具体代码如下:
.box .container {
width: 200px;
height: 100px;
background-color: #0f0;
margin: auto;
/* width: 100%; */
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
刷新浏览器,效果如下:
使用用绝对定位实现居中,好处就是这种不会存在兼容性问题,而如果使用 flex
布局方式实现垂直和水平居中是存在兼容性问题的。
如果希望绝对定位元素的宽高和定位参照对象一样,可以给绝对定位元素设置如下属性:
left: 0; right: 0; top: 0; bottom: 0; margin: 0;
如果希望绝对定位元素在定位参照对象中居中显示,可以给绝对定位元素设置以下属性
left: 0; right: 0; top: 0; bottom: 0; margin: auto;
另外绝对定位元素要设置具体的宽高值并且小于参照对象的宽高。
一种特殊性情况
在前面的绝对定位元素的参照对象宽度的公式中,
div.box = div.container 的宽度 + ml + mr + right + left
那么我把 margin-right: 0; margin-left: 0;
的情况下, 并且 left
和 right
的不设置的情况下,默认为 auto
,这种情况下会居中吗?
.box .container {
width: 200px;
height: 100px;
background-color: #0f0;
margin: 0 0;
/* width: 100%; */
position: absolute;
/* left: 0;
right: 0;
top: 0;
bottom: 0; */
}
刷新浏览器,效果如下:
并没有居中,设置为 auto
并不一定会居中。
值设置为 auto 的效果总结
设置为 auto
的意思是交给浏览器来处理,原来在哪里现在还在哪里。
如果 width
设置为 auto
,会有以下几种情况:
- 对于行内非替换元素来说,width 会包裹内容
- 对于块级元素来说,width 会包含块的宽度
- 对于绝对定位元素来说,width 会包裹内容
转载自:https://juejin.cn/post/7300102080903462923