0

Stumped.

I have a basic card with an image and a text tag I want to float over the image.

The tag should have a background color behind the text and above the image.

The background of the text goes behind the image instead.

https://codepen.io/Mikeritteronline/pen/LwJYaR


html

<div class="card">
  <div class="card__image">
    <img src="https://placehold.it/1024x768" alt="">
  </div>
  <div class="card__tag">
    <p>Image Tag</p>
  </div>
</div>


css

img {
  max-width:100%;
  height: auto;
  margin: auto;
  }
.card {
  max-width: 320px;
  margin: auto;
  }
.card__tag p{
  background: blue;
  color: lime;
  padding: 0.25rem;
  margin-top: -3rem;
}
mike
  • 1,786
  • 2
  • 19
  • 31
  • Google `absolute` and `fixed` positioning and `z-index` I guess these will do it. Also here's a helpful link: https://www.tutorialrepublic.com/faq/how-to-position-text-over-an-image-using-css.php – mahmoudafer Aug 09 '19 at 11:20
  • explain clearly your question? – Ranjith v Aug 09 '19 at 11:25

4 Answers4

3

You can add position to achieve what you want.

.card {
  position: relative;
}
.card__tag p {
  position: absolute;
}
Kim Hogeling
  • 641
  • 6
  • 14
1

add

position: relative 

to the p tag like

.card__tag p{
  background: blue;
  color: lime;
  padding: 0.25rem;
  margin-top: -3rem;

  position: relative;
}
Simon Hansen
  • 622
  • 8
  • 15
1

Add position:relative to .card and position:absolute to .card__tag

Here is the updated fiddle:

img {
  max-width: 100%;
  height: auto;
  margin: auto;
}

.card {
  max-width: 320px;
  margin: auto;
  position: relative;
}

.card__tag p {
  background: blue;
  color: lime;
  padding: 0.25rem;
  margin-top: -3rem;
}

.card__tag {
  position: absolute;
}
<div class="card">
  <div class="card__image">
    <img src="//placehold.it/1024x768" alt="">
  </div>
  <div class="card__tag">
    <p>Image Tag</p>
  </div>
</div>
Vikas Jadhav
  • 4,597
  • 2
  • 19
  • 37
1

I think its best if you position the div not the p like so: (also generaly try to avoid positioning absolute if you do not have to)

img {
  max-width:100%;
  height: auto;
  margin: auto;
  }
.card {
  max-width: 320px;
  margin: auto;
  }

.card__tag{
  z-index: 1;
  position:relative;
  top: -3rem;
}
.card__tag p{
  background: blue;
  color: lime;
  padding: 0.25rem;
}
<div class="card">
  <div class="card__image">
    <img src="//placehold.it/1024x768" alt="">
  </div>
  <div class="card__tag">
    <p>Image Tag</p>
  </div>
</div>
Victor Radu
  • 2,262
  • 1
  • 12
  • 18