盒子
盒子
文章目录
  1. 当display-table-cell的元素设置了position-absolute失效的bug

当display:table-cell的元素设置了position:absolute失效的bug

当display-table-cell的元素设置了position-absolute失效的bug

问题复现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head>
<title>01 Demo</title>
<style type="text/css">
#banner {
position: relative;
display: table-cell;
width: 200px;
height: 200px;
overflow: hidden;
text-align: center;
vertical-align: middle;
background-color: #f00;
}
</style>
</head>
<body>
<div id="banner">
<img width="50" height="50" src="https://lh3.googleusercontent.com/-aVJFt11BsXk/AAAAAAAAAAI/AAAAAAAAAAA/AKB_U8u7r4-EjGt5Fx6T-2ESqGLFt4xfxQ/s32-c-mo/photo.jpg"/>
</div>
</body>
</html>

预览效果:

display-cell-relative

但是当把#banner的postion属性设置成absolute时,display:table-cell就失效了,#banner就变回了普通的display:div元素了。

1
2
3
4
5
6
7
8
9
10
#banner {
position: absolute; /*从relative改成absolute*/
display: table-cell;
width: 200px;
height: 200px;
overflow: hidden;
text-align: center;
vertical-align: middle;
background-color: #f00;
}

预览效果

display-cell-absolute

原因是:

The declaration position: absolute takes your element out from wherever it is and place it relative to innermost element that is not declared static. In no longer participate in the alignment of any other element, hence it no longer serve as table-cell (the declaration has no effect).

声明为absolute将元素从任何位置移出,并将其放置为相对于未声明为static的最内层元素。 不再参与任何其他元素的对齐,因此它不再用作表格单元格(声明没有效果)[google翻译]。

就是应用positioin absolute之后table-cell的属性就会失效。

解决办法:

  • 也就只能再包裹一层元素了。不要把absolute应用在table-cell的属性上!
  • 不用table-cell的话,用css3的flex也能解决垂直居中的问题,而且无absolute的这个问题。Flex 布局教程

看MDN上,对display属性的定义和对position属性的定义未找到相关信息。就用了stakoverflow上的这个答案。

参考资料:

1、《why-display-table-cell-is-broken-when-position-absolute》

2、《Table Cell and Position Absolute》

3、《display MDN》

4、《position MDN》

支持一下
扫一扫,支持lcoder