htmlcssposition

HTML Why does my text start outside the div?


#image-container{
    position: relative;
    display: block;
}

#image-container img{
    width: 100%;
    height: auto;
    display: block;
}

#short-text{
    position: absolute;
    font-size: 2vw;
    color: black;
}

<div id="image-container">
   <img src="./path/to/image.png" alt="Some image">
   <span id="short-text">
      Short text
   </span> 
</div>

Why does the text appear right under the image instead of over it ?

I tried changing position and display of '#image-container', '#image-container img' and '#short-text'. I expected one of those combination to let the short text to appear over the image and the subsequent content to appear under the image but I can't have both


Solution

  • You need to adjust the positioning of the #short-text element within the #image-container.

    <div id="image-container">
        <img src="./path/to/image.png" alt="Some image">
        <span id="short-text">Short text</span>
    </div>
    
    #image-container {
        position: relative;
        display: block;
    }
    
    
    #image-container img {
        width: 100%;
        height: auto;
        display: block;
    }
    
    #short-text {
        position: absolute;
        top: 0; /* Adjust the value as needed */
        left: 0; /* Adjust the value as needed */
        font-size: 2vw;
        color: black;
    }
    

    This setup ensures that the text will appear over the image, positioned according to the top and left properties. Adjust these properties to place the text exactly where you want it over the image.