Search code examples
htmlcsspositioning

Positioning sibling elements one over the other


I have a TABLE with multiple rows. Within each row one of the TD elements contains several DIV elements that:

  1. can have any dimension but all of them (within one TD) have the same pixel dimension
  2. have to be positioned one on top of the other
  3. containing TD needs to resize according to child DIV elements
  4. One DIV will be displayed at a time (statically)
  5. when changing from one to the other fading will be used (so two of them will be displayed at the same time)
  6. there will never be more than two of them displayed at the same time

This is a simplified example of such a table

<table>
    <tr>
        <td>Name</td>
        <td>
            <div>First</div>
            <div>Second</div>
            ...
            <div>Last</div>
        </td>
        <td>Additionals</td>
    </tr>
    <tr>
        <td>Name</td>
        <td>
            <div>First</div>
            <div>Second</div>
            ...
            <div>Last</div>
        </td>
        <td>Additionals</td>
    </tr>
    ...
</table>

The obvious solution would be to set

div
{
    position: absolute;
}

This will automatically position DIV elements on top of each other (according to flow layout), but TD dimension will stay as if it contains no child elements. Overflow doesn't do anything because child elements are absolutely positioned.

td
{
    overflow: auto;
}

How should I make this work?


Solution

  • Do you know the size of the divs before hand? If so, you can just give a wrapper div those dimensions:

    <td>
        <div class="wrapper">
           <div>1</div>
           <div>2</div>
           <div>3</div>
        etc...
    

    If you don't won't know the size, then, since you are already using JS, you could grab the size of the first child div of wrapper and then set the wrapper dimensions via JS.

    UPDATE:

    The only way I can think of doing this with CSS all by itself would be to have the first DIV render twice. The first instance set to position: relative, and then it's duplicate, like the rest, can be set to position: absolute. This clone then acts like a shim. You could set visibility: hidden if you want to make sure it doesn't show up visually (but still takes up the proper space). The drawback to this, however, is that you now have content duplicated on your page, which may not be ideal from an SEO and/or accessibility POV.

    I'd probably go the JS route and grab the dimensions after the page loads.