TitanicSwimmer
TitanicSwimmer

Reputation: 299

How to force button, inside of parent div, in front of div. I've tried z-index to no avail

I was wondering if there is a fix.

<div id="div1" style="position: fixed; top:0; z-index:1; background:white;">
 </div>

<div id="div2" style="position: absolute; top:100; z-index:0;">
    <table>
        <tr>
            <td>
              <input type="button" style="position: fixed; top:50; z-index:2;" />
            </td>
        </tr>
        <tr>
            <td>
                some text that is longer than the width of the button
            </td>
        </tr>
    </table>
</div>

I want the button in front of <div id="div1"> and I want the button and <div id="div1"> in front of <div id="div2">. But what I'm getting is <div id="div1"> in front of the button.

I'm assuming that the reason is because the button is nested in the <div id="div2"> that is behind <div id="div1">. Anyone have any ideas besides restructuring?

I am doing this so that the button will scroll on top of the the text when I scroll down on the page.

The text is longer than the width of the button, so I do the whitespace div so you don't see the extra text coming out of the side of the button.

The answer to this question confirms my suspicions I think, but I would like a way around this. Basically I want the button in front of div1 and div1 in front of div2.

Upvotes: 1

Views: 1721

Answers (2)

Marc Audet
Marc Audet

Reputation: 46785

Here is one technique that may be helpful.

Using your existing HTML, I took out your inline styles and used the following CSS:

#div1 {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 50px;
    background-color: gray;
    z-index: 1;
}
#div2 {
    position: absolute;
    top: 50px;
}

and the following jQuery:

$('#div2 input').prependTo($('#div1'));

The trick is to move the button out of #div2 and into #div1 using jQuery's DOM manipulation function .prependTo().

Styling the CSS is pretty straightforward after that.

Fiddle Demo: http://jsfiddle.net/audetwebdesign/Gv6XQ/

Upvotes: 2

Tom Pietrosanti
Tom Pietrosanti

Reputation: 4294

To just get the button on top, remove position: absolute; from div2.

This might break other things you're trying to do, but...

You can still give a margin-top: 100px; which might keep the positioning intact, depending on your context.

If you can change the .net code to alter the HTML structure, this might be easier.

Upvotes: 1

Related Questions