Miguel Moura
Miguel Moura

Reputation: 39484

Place DIV over other DIV and Image

I have the following HTML (Plunker Example):

<div class="first">
  <img src="http://placehold.it/350x150">
</div>

<div class="second">
  Lorem Ipsum ...
</div>        

I need to place part of the second DIV over the first DIV so I used:

body {
  text-align: center;
}

.first {
  background-color: orange;
  z-index: 100;
}

.first img {
  display: block;
  margin: 0 auto;
}

.second {
  background-color: red;
  margin: -80px 0 auto;
  z-index: 200;
}

What is strange is the text in second DIV appears over the image but not the second DIV. Red should be over the image as the text is ...

Does anyone knows how to fix this?

Upvotes: 0

Views: 114

Answers (4)

user7273509
user7273509

Reputation:

position: relative; in the second div

Upvotes: 2

Hanif
Hanif

Reputation: 3795

You can try with following code:

.second {
    background-color: red;
    margin: 0 auto;
    z-index: 200;
 }

Upvotes: 0

Jon Uleis
Jon Uleis

Reputation: 18649

By default, <div> elements are position: static which ignores positional CSS including z-index. Adding position: relative to the .second element allows z-index to work properly.

I also changed the negative margin to top: -80px, which is cleaner.

body {
  text-align: center;
}

.first {
  background-color: orange;
  z-index: 100;
}

.first img {
  display: block;
  height: auto;
  outline: 0;
  width: 100%;
}

.second {
  background-color: red;
  z-index: 200;

  position: relative;
  top: -80px;
}
<body>

  <div class="first">
    <img src="http://placehold.it/350x150">
  </div>

  <div class="second">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
    software like Aldus PageMaker including versions of Lorem Ipsum.
  </div>


</body>

Upvotes: 1

Fueled By Coffee
Fueled By Coffee

Reputation: 2569

Try relatively positioning the second div:

.second {
  background-color: red;
  margin: 0 auto;
  position:relative;
  z-index: 200;
}

Upvotes: 1

Related Questions