Why is the CSS attribute for 'text' block in the below code not being applied?

Viewed 39

I am trying to create div elements through Javascript, and add attributes to them through CSS.

There are two attributes:

  1. One for the background. This is working fine.
  2. One is for text. I am trying to add attributes to it in the say way I am adding attributes to the background, through id of the created div element. But due to some reason "TEXT" is not being displayed.

I have narrowed down the problem to diva.id="text";. But I am not sure what is wrong with it.

//grey block
var div=document.createElement('div');
div.id="overlay";
document.body.appendChild(div);
document.getElementById("overlay").style.display = "block";

//text
var diva=document.createElement('div');
diva.id="text";
var text= document.createTextNode('TEXT');
diva.appendChild(text);
document.body.appendChild(diva);
#overlay {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 2;
  cursor: pointer;
}

#text {
  position: absolute;
  color: white;
}

1 Answers

The problem is that the elements overlap, and you have z-index: 2 on the #overlay element, which means it's closer to the viewer than the default would be. But the other one is at the default distance. Since the #overlay is not transparent, it completely hides the #text element.

Here you can see what happens if I add z-index: 2 to #text, just by way of example:

//grey block
var div=document.createElement('div');
div.id="overlay";
document.body.appendChild(div);
document.getElementById("overlay").style.display = "block";

//text
var diva=document.createElement('div');
diva.id="text";
var text= document.createTextNode('TEXT');
diva.appendChild(text);
document.body.appendChild(diva);
#overlay {
  position: fixed;
  display: none;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  z-index: 2;
  cursor: pointer;
}

#text {
  position: absolute;
  color: white;
  z-index: 2;
}

Battling z-indexs usually isn't what you want, though (although sometimes it is). You may want to structure things differently so the two elements default to the same layer or similar.

Related