user1850886
user1850886

Reputation: 123

Can I absolutely position an element in the top right corner of a <td> element?

I have a table and I need the cells to have an element positioned in the upper right corner of each cell.

I've read several other questions asking the same thing but none of them seem to fix the problem.

One solution I have read say to wrap the inside of the cell in a div with relative positioning, but that doesn't work because the div doesn't fill the whole cell, even with height and width set to 100%.

The other solution I have read says to manually set the height of the cells and manually set the height of the div to the same value. This doesn't work for me either because the tables are being dynamically generated and I can't guarantee a certain size for the cells.

Here's some code that illustrates the problem:

<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>   

Here's what that example looks like http://jsfiddle.net/hqtEQ/

Is there any way I can get the red div into the top right corner of every cell?

Upvotes: 5

Views: 5509

Answers (2)

Ilya Streltsyn
Ilya Streltsyn

Reputation: 13536

Firefox seems to be the only browser that can't absolutely position something directly in the td with position:relative (because of the bug 63895). Other browsers don't have any problems here. And since version 22, Firefox has supported the latest syntax of Flexbox which a) can emulate table behavior, b) doesn't have problems with position: relative. What about using it as a workaround just for 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

Upvotes: 1

Adrian Wragg
Adrian Wragg

Reputation: 7401

The default vertical alignment of a td is centered; so, if you're not worried about the other content in the cell just replace

<td>

with

<td style="vertical-align: top;">

(or add a CSS class to this effect) and your layout will work as intended.

See http://jsfiddle.net/hqtEQ/1/

Upvotes: 5

Related Questions