Josh B Josh B - 4 months ago 7
HTML Question

Style not appearing on fixed div

I have a div that I want to appear on top of other divs and this is the code for it:

function displayMessage(content) {
//content is a string
var newElement = document.createElement('div');
newElement.innerHTML = content;
newElement.style.position = "fixed";
newElement.style.left = "50%";
newElement.style.right = "50%";
newElement.style.top = "50%";
newElement.style.bottom = "50%";
newElement.style.backgroundColor = "#99ff33";
newElement.style.border = "thick solid";
newElement.style.display = "inline-block";
newElement.style.zIndex = 100
}


When I do this the background color does not appear and the border is just a dot on the screen. However when I comment out the position everything works fine but my div is on the bottom of the screen.

function displayMessage(content) {
//content is a string
var newElement = document.createElement('div');
newElement.innerHTML = content;
//newElement.style.position = "fixed";
newElement.style.left = "50%";
newElement.style.right = "50%";
newElement.style.top = "50%";
newElement.style.bottom = "50%";
newElement.style.backgroundColor = "#99ff33";
newElement.style.border = "thick solid";
newElement.style.display = "inline-block";
newElement.style.zIndex = 100
}


How can I have the background color and border appear and still have the div's style be fixed?

Answer

You have set the 'left' and 'right' properties to 50%, meaning you have forced the left of the div to be 50% of the screen width away from the left of the screen (ie, the middle of the screen) and the same for the right. So it cannot be any more than 0 pixels.

Try using a slightly lower value than 50%, or set it using a calc and a set width, for example:

newElement.style.left = "calc('50% - 100px')";
newElement.style.width = "200px";

This fixes the left position to 100px less than 50% of the screen width. So that combined with a 200px width will center it, if that is what you desire. Note that the 'right' style is no longer necessary. Then do the same for the top and bottom.

Comments