Skip to content Skip to sidebar Skip to footer

Making Text Above A Line On Image

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. The problem

Solution 1:

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:

functionsetTextPosition() {
  // get html elementsvar image = document.querySelector('#background_pic');
  var text = document.querySelector('#text');
  
  // get height of imagevar 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 resizewindow.addEventListener('load', setTextPosition);
window.addEventListener('resize', setTextPosition);
#text{
  position: absolute;
  top: 685px;
}

html,body {
    margin:0;
    padding:0;
}


#background_pic
{
  width: 100%;
}
<imagesrc="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><divid="text">
hello world
</div>

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

Solution 2:

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:100px0;
}

.underline {
  border:3px solid black;
  border-radius:10px;
}
<divid="wrapper"><div>Hello World!</div><divclass="underline"></div></div>

Post a Comment for "Making Text Above A Line On Image"