我有一个表,我需要单元格在每个单元格的右上角都有一个元素。
我读过其他几个问题,问的都是同样的问题,但似乎没有一个能解决问题。
我读过的一个解决方案是,用相对定位将单元格内部包裹在div中,但这不起作用,因为即使高度和宽度设置为100%,div也不会填充整个单元格。
我读过的另一个解决方案是手动设置单元格的高度,并手动将div的高度设置为相同的值。这对我来说也不起作用,因为表是动态生成的,我不能保证单元格有一定的大小。
以下是一些说明问题的代码:
<table border="1">
<tr>
<td>
<div style="position:relative; height: 100%; background: yellow;">
<p>This is some content</p>
<div style="position:absolute; right:0px; top:0px; background: red;">
absolute
</div>
</div>
</td>
<td>
<div style="position:relative; height: 100%; background: yellow;">
<p>This is some content</p>
<p>This is some content</p>
<p>This is some content</p>
<p>This is some content</p>
<p>This is some content</p>
<p>This is some content</p>
<div style="position:absolute;right:0px; top:0px; background: red;">
absolute
</div>
</div>
</td>
</tr>
下面是这个例子的样子http://jsfiddle.net/hqtEQ/
有没有办法把红色的div放到每个单元格的右上角?
td
的默认垂直对齐居中;所以,如果你不担心单元格中的其他内容,只需更换
<td>
带有
<td style="vertical-align: top;">
(或者为此添加一个CSS类),您的布局将按预期工作。
请参阅http://jsfiddle.net/hqtEQ/1/
Firefox似乎是唯一一个不能用position:relative
直接在td
中定位内容的浏览器(因为错误63895)。其他浏览器在这里没有任何问题。自版本22以来,Firefox支持Flexbox的最新语法,a)可以模拟表行为,b)position: relative
没有问题。把它作为Firefox的变通方法怎么样?
td {
position: relative;
background: yellow;
}
:-moz-any-link > html, tr {
display: flex;
flex-direction: row;
}
:-moz-any-link > html, td {
display: flex;
flex-direction: column;
justify-content: center;
}
Fiddle