Search code examples
htmlcsstextbackground-image

text over image without using relative position or negative margins


I am trying to put text over an image. Something like this (i have changed the background image for propriety reasons)

enter image description here

The tool/app i am working with has following limitations -

  • Using negative margins don't work
  • Using position:absolute and position:relative don't work
  • fancy stuff like grid and flexbox also dont work

I know i know. You all are thinking "what the heck is it?". But if any one of you used salesforce visualforce email templates, you will know what i am talking about.

So i need to implement it without them. I want the image to retain its aspect ratio as i compress and expand browser window.

When i use background image html tag, i notice that background image does not maintain it's aspect ratio. In full screen mode, it stretches horizontally (actual image i am using has drawing of animated characters in it, which visible look horizontally stretched out)

<div style="color:white; background-image: url('images\background.png');max-width: 100%;height: auto;overflow: hidden;background-size: 100% 100%;">

But when i use an img tag, image fits the full screen nicely, and maintains its aspect ratio when i change browser window size

<img src="images/background.png" style="display: block;max-width: 100%;min-width: 100%;height: auto">

So i figured i need to come up with a solution without using background image (or negative margin or position:relative) and somehow get text on it.

I read a post where a guy suggested a hack using tables - How to put text over an image without absolute positioning or setting the image as backbround

It seems to work to an extend. I need help fixing it. Here is the final code i have-

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <div>
        <table>
          <tr>
            <td></td>
            <td rowspan=2 colspan=2><img src="images/background.png" style="display: block;max-width: 100%;min-width: 100%;height: auto"></td>
          </tr>  
          <tr>
            <td rowspan=2 colspan=2><h1 style="margin-top: 5rem;padding-bottom: 25rem; text-align: center; color:white">Thank you for submitting feedback</h1></td>
          </tr>  
        </table>
    </div>
</body>
</html>

Issue i am facing is if i compress browser window too much, the text float above the blue image, as shown below

enter image description here

Any help would be appreciated. Both text and image are part of table. Is there a way to make sure they stay within table boundaries, so they stay overlapped?


Solution

  • You need to align the image on the top in <td> element, because its default is middle. That is why it is being aligned that way and giving space above and below.

    So, add vertical-align: top to <td> element.

    td {
      vertical-align: top;
    }