Miguel Moura
Miguel Moura

Reputation: 39364

Place image behind divs using CSS

I have the following markup (Fiddle Example Here: http://jsfiddle.net/9gvj11o5/8/)

<div class="header">           
  <div class="image">
    <img src="http://placehold.it/2200x800" alt=""/>
  </div>    
  <div class="menu">This is the menu</div>    
  <div class="tools">These are the tools</div>        
</div>    
<div class="content">content</div>    

And the following CSS:

.header {
  position: relative;
}

.image {
  position: absolute;
}

img {
  width: 100%;
  height: auto;
  outline: 0;
}

I need the image to be responsive and have 100% width aligned to top.

But I also need the menu and tools to be over the image and having their normal flow.

Content should be after the image, so after the header.

The image would be the "background" of the header div. (I cannot use background-image)

I am using position but the menu and tools disappear the moment I use it.

What am I missing? Do I need another wrapper div somewhere?

Upvotes: 0

Views: 100

Answers (2)

dippas
dippas

Reputation: 60543

I would wrap the 2 divs .menu & .tools so you need only to apply z-index to the wrapper div instead of each child. which make .menu & .tools (wrapped) in front of the .image.

then change position:absolute to position:relative to .image in order to have .content below header.

Below you can see the snippet, very lightweight.

.header {
    position: relative;
}
.image {
    position: relative;
    z-index:1
}
#menu-all {
    position:absolute;
    top:0;
    z-index:2
}
img {
    width: 100%;
    height: auto;
    outline: 0;
}
<div class="header">
    <div class="image">
        <img src="http://placehold.it/2200x800" alt="" />
    </div>
    <div id="menu-all">
        <div class="menu">This is the menu</div>
        <div class="tools">These are the tools</div>
    </div>
</div>
<div class="content">content</div>

Upvotes: 1

Patrick Moore
Patrick Moore

Reputation: 13344

You can use z-index to define the layer order of your elements. The smaller the number, the closer to the "bottom" of the stack. So we give the img a very small number, and menu and tools a very large one.

.header {
    position: relative;
}

.image {
    position: absolute;
    z-index: 1; /* here you can use -1 as Paulie_D points out in the comments */
}

img {
    width: 100%;
    height: auto;
    outline: 0;
    z-index: 2; /* here you can use -1 as Paulie_D points out in the comments */
}

.menu {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 888; /* You can remove this declaration entirely if you set -1 above */
}

.tools {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 888; /* You can remove this declaration entirely if you set -1 above */
}

Upvotes: 1

Related Questions