Jakub M.
Jakub M.

Reputation: 33817

Display <div> behind other div

I have a <div> (parent, e.g. 100px x 100px) and other <div>s (children, e.g. four squares of 50px x 50px) inside the parent.

<div id="parent">
  <div id="ch1">...</div>
  <div id="ch2">...</div>
  ...
</div>

The children fill the parent entirely. Now, I want to show and hide the text in the parent, but I want it to be displayed behind the children. If I just do:

<div id="parent">TEXT
  <div id="ch1">...</div>
  <div id="ch2">...</div>
  ...
</div>

it breaks the children layout. z-index: -1 does not work. Any idea how to solve it?

Upvotes: 0

Views: 12698

Answers (3)

Jamie Dixon
Jamie Dixon

Reputation: 53991

While you could position each of the inner divs using absolute position, it makes more sense to me to position the text absolutely rather than the boxes. Consider:

HTML

<div id="parent"><span>Text</span>
  <div>...</div>
  <div>...</div>
  <div>...</div>
  <div>...</div>
</div>

CSS

#parent{
    width:105px;
    height:105px;
    border:1px solid blue;
    margin:0;
    padding:0;
    position:relative;
}

#parent div{
    width:50px;
    height:50px;
    border:1px solid red;
    float:left;
}

#parent span{
    position:absolute;
    top:0;
    left:0;
}

Working demo: http://jsfiddle.net/Eqd4j/

This method is probably a bit more flexible than setting each child div to be positioned absolutely.

Upvotes: 4

Chains
Chains

Reputation: 13157

One way -- Use absolute positioning.

Upvotes: 2

John Stimac
John Stimac

Reputation: 5493

CSS:

#parent{
    position:relative;
}

#ch1{
    position:absolute;
    top:0;
    left:0;
}

#ch2{
    position:absolute;
    top:0;
    left:50px;
}

#ch3{
    position:absolute;
    top:50px;
    left:0;
}

#ch4{
    position:absolute;
    top:50px;
    left:50px;
}

Upvotes: 5

Related Questions