making text above a line on image

前端 未结 2 1236
南旧
南旧 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%;
    }
    <image src="https://vignette.wikia.nocookie.net/uncyclopedia/images/4/47/Horiz-line.JPG/revision/latest/scale-to-width-down/600?cb=20050929041542" id="background_pic"></image>
    
    <div id="text">
    hello world
    </div>

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

    0 讨论(0)
  • 2021-01-22 01:29

    If all you really want is text above a black line that has a radius on each end, then you can accomplish much simpler with just CSS.

    By wrapping the text and the line in another element, you can then create space above and below the two:

    #wrapper {
      margin:100px 0;
    }
    
    .underline {
      border:3px solid black;
      border-radius:10px;
    }
    <div id="wrapper">
      <div>Hello World!</div>
      <div class="underline"></div>
    </div>

    0 讨论(0)
提交回复
热议问题