SupaDupa
SupaDupa

Reputation: 181

Use image as container for text instead of div

I'm trying to display a short image description at the bottom of an image, right now it looks like this: https://www.bootply.com/render/Gwde8WHtot

But i want the green background to align with the image (not the red border), meaning the width and height attribute of the text should respond to the image, not the container it is in.

This is my current code:

// CSS
.textoverimage {
    position: absolute;
    background: green;
    font-family: 'Roboto', sans-serif;
    font-size: 15px;
    color: white;
    word-wrap: break-word;
    text-align: center;
    width: 100%;
    height: auto;
    bottom: 0;
    left:0;
    padding: 5px;
    z-index: 5;
    border-radius: 0px 0px 3px 3px;
}

// HTML
<div class="container">
  <div class="row">
    <div id="0" class="col-6 col-sm-4 col-md-3 col-lg-2" style="margin-top:7px;margin-bottom:7px;border:1px solid red">
      <a href="#" class="d-block mb-12">
        <img class="rounded  img-fluid" src="http://via.placeholder.com/160x230.jpg">
        <div class="textoverimage">Random</div>
      </a>
    </div>
  </div>
</div>

Full example: https://www.bootply.com/Gwde8WHtot

Is there any way to achieve this? If the column/image resizes when you resize the browser, the text should be responsive as well. Any help is greatly appreciated! Thanks in advance.

Upvotes: 0

Views: 1014

Answers (2)

Sam Ryan
Sam Ryan

Reputation: 7

You could set the ('.d-block mb-12') div as a position:relative and then make the text position:absolute (hoping that the div covers the entire image. Once this is done you could use:

.textoverimage{
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin: 0 auto;
}

then the parent div will be:

.d-block {
postion:relative;
width:100%;
height:100%;
}

That should work, hoping that the .d-block div has a parent div with a width/height set in PX if not drop the height and width attr and then you should be perfect.

Don't forget the Margin: 0 auto;

If it doesn't center absolute then maybe try adding

display:block;      or      display:inline-block;

Hope this helps

Upvotes: 0

nanobar
nanobar

Reputation: 66355

You're almost there, you just need to add:

.d-block {
  position: relative;
}

Since the anchor is wrapping around the image, you set a relative boundary there, meaning that a position: absolute inside that will be relative to those bounds.

Upvotes: 1

Related Questions