making text above a line on image

前端 未结 2 1235
南旧
南旧 2021-01-22 01:01

I am working on a project where I am trying to make a text above a line on the image on all browser sizes. This will be more clear once you see the codpen link below.

T

2条回答
  •  情歌与酒
    2021-01-22 01:04

    You set the #text to a static position from the top, which will not work on all screen sizes (which may vary), which will cause the image to vary.

    You want to dynamically set the text based on the image height. Here is an example using JavaScript:

    function setTextPosition() {
      // get html elements
      var image = document.querySelector('#background_pic');
      var text = document.querySelector('#text');
      
      // get height of image
      var imageHeight = image.clientHeight;
    
      // dynamically set text position (the '-20' is meant to make the text stay above the line)
      text.style.top = imageHeight/2 - 20 + 'px';
    }
    
    
    // set the text position on load and resize
    window.addEventListener('load', setTextPosition);
    window.addEventListener('resize', setTextPosition);
    #text{
      position: absolute;
      top: 685px;
    }
    
    html,body {
        margin:0;
        padding:0;
    }
    
    
    #background_pic
    {
      width: 100%;
    }
    
    
    
    hello world

    Try the above snippet, and see how resizing it always allows the text to stay right above the line.

提交回复
热议问题