Mykita
Mykita

Reputation: 467

How can I put a <div> over an image?

I am trying to place a directly on top of an image.

I have tried by giving both the image and the z-index values (because normally the element with higher z index appears on the top, right?)

Upvotes: 2

Views: 6435

Answers (2)

Leo Van Deuren
Leo Van Deuren

Reputation: 435

Here is an inline version of the same answer that I was working on.

<div class="parent" style="position: relative;">
  <img src="http://placekitten.com/700/500?image=13">
  <div style="position: absolute; top: 250px; left: 170px;color: red;font-size: 100px;">My Div</div>
</div>

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

You have to use CSS for this. Basically, HTML and CSS co-exist (check the dev tools, even if you haven't given any CSS, it will be having some CSS properties).

What you might need is something like this:

figure,
figcaption {
  margin: 0;
  padding: 0;
}

figure {
  display: inline-block;
  position: relative;
}

figure img {
  display: block;
}

figure figcaption {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  padding: 10px;
  border-radius: 5px;
}
<figure>
  <img src="https://i.imgur.com/3rcJO2J.jpg" alt="Image" width="200" />
  <figcaption>Hello!</figcaption>
</figure>

Preview

preview

Note: Use of z-index will work and be effective only if the element is given a position of absolute or relative. ps: z-index is CSS.

Upvotes: 6

Related Questions