Search code examples
javascriptpositioninlinefixedabsolute

Text on image not working with "position fixed"


I am having some problem with text on an image (inline JS element). It is a countdown timer that I want to show on top of an image. The image is also fixed to a screens window size.

The code is here: https://jsfiddle.net/Lo7soz5f/

If I remove "position:fixed" from #forsidediv it works, but then the image is no longer fitted to the window size. However, if I put it back on, the timer no longer shows on top of the image.

HTML:

<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>onepageskiw</title>
<link href="styles.css" rel="stylesheet" type="text/css">
<script src="js.js"></script>
</head>

<body>

<div id="countdowner">
  <div id="countdown"></div>
  <div id="newcountdown"></div>
</div>

<div id="forsidediv">
  <img id="forsidepic" src="https://images.unsplash.com/14/unsplash_524000a90aaad_1.JPG?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=dc7275b6369c623d975484143fbb6a17">
</div>

Script:

<script>
  CountDownTimer('02/19/2017 10:1 AM', 'countdown');
  CountDownTimer('02/20/2017 10:1 AM', 'newcountdown');

  function CountDownTimer(dt, id) {
    var end = new Date(dt);

    var _second = 1000;
    var _minute = _second * 60;
    var _hour = _minute * 60;
    var _day = _hour * 24;
    var timer;

    function showRemaining() {
      var now = new Date();
      var distance = end - now;
      if (distance < 0) {

        clearInterval(timer);
        document.getElementById(id).innerHTML = 'EXPIRED!';

        return;
      }
      var days = Math.floor(distance / _day);
      var hours = Math.floor((distance % _day) / _hour);
      var minutes = Math.floor((distance % _hour) / _minute);
      var seconds = Math.floor((distance % _minute) / _second);

      document.getElementById(id).innerHTML = days + 'days ';
      document.getElementById(id).innerHTML += hours + 'hrs ';
      document.getElementById(id).innerHTML += minutes + 'mins ';
      document.getElementById(id).innerHTML += seconds + 'secs';
    }

    timer = setInterval(showRemaining, 1000);
  }

</script>

CSS:

@charset "utf-8";

body {
margin:0;   
}

#countdowner {
color:white;
padding:1em;
position:absolute;

}

#forsidediv {
position:fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
text-align: center;
}

#forsidepic {
width: 100%;
}

Solution

  • If i understand correctly: https://jsfiddle.net/Lo7soz5f/4/ Just change your div order:

    <div id="forsidediv">
      <img id="forsidepic" src="https://images.unsplash.com/14/unsplash_524000a90aaad_1.JPG?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=dc7275b6369c623d975484143fbb6a17">
    </div>
    
    <div id="countdowner">
      <div id="countdown"></div>
      <div id="newcountdown"></div>
    </div>