0
* {
  margin: 0;
  padding: 0;
}

div#parent {
  position: relative;
}

div#container {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

img {
  position: absolute;
  width: 100%;
}
<body>
  <div id="parent">
    <img src="bg.jpg" draggable="false">
    <div id="container"></div>
  </div>
</body>

I'm using the <img> as a background. I want the #container to be on top of the "background" and to have the same dimensions as the background. How may I achieve that without JavaScript?

Chris Happy
  • 7,088
  • 2
  • 22
  • 49

2 Answers2

1

Try the following code

<html>
  <head>
    <style>
      * { margin: 0; padding: 0; }
      div#parent { position: relative; }
      div#container { position: absolute; left:0; top:0; z-index:100; width: 100%; height: 100%; background-color: rgba(0,0,0, 0.5); }
      img { position: relative; width: 100%; }
   </style>
 </head>
   <body>
     <div id="parent">
       <img src="bg.jpg" draggable="false"/>
       <div id="container"></div>
     </div>
   </body>
</html>
shaina
  • 212
  • 1
  • 10
0

You assigned position:relative to parent div but you not define the child that where the child is set behalf of it's parent, when you assign top and left position the child which has position:absolute get set top and left of the parent.

Like following

Css changes

div#container {
  position: absolute;
  width: 100%;
  top: 0; /* Add this */
  left: 0; /* Add this */
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}
img {
  width: 100%;
  /* Remove the absolute */
}

* {
  margin: 0;
  padding: 0;
}

div#parent {
  position: relative;
}

div#container {
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

img {
  width: 100%;
}
<div id="parent">
  <img src="http://lorempixel.com/400/200/sports" draggable="false" />
  <div id="container"></div>
</div>
LKG
  • 4,152
  • 1
  • 11
  • 21