我正在动态地组装divs within divs并向每个内部div添加文本--使用Javascript列表适配器构建一个列表。内部list divs按需要显示,但每个list div中的相应text divs没有:
示例:

正如您在图像中看到的,右边红色文本中的text div略高于左侧绿色文本。我已经为每个属性设置如下:
在Javascript中,我使用以下方法将它们添加到一个循环中:
var divGreen = document.createElement("div");
divGreen.style.position = "relative";
divGreen.style.width = "10%";
divGreen.style.left = "100%";
divGreen.style.top = "100%";
divGreen.style.marginLeft = "-40%";
divGreen.style.marginTop = "-20%";
divGreen.style.color = "green";
divGreen.style.textAlign="left";
divGreen.style.backgroundColor = "#cccccc";
divGreen.innerHTML = 'Text';
div.appendChild(divGreen);
var divRed = document.createElement("div");
divRed.style.position = "relative";
divRed.style.width = "10%";
divRed.style.left = "100%";
divRed.style.top = "100%";
divRed.style.marginLeft = "-20%";
divRed.style.marginTop = "-20%";
divRed.style.color = "red";
divRed.style.textAlign="left";
divRed.style.backgroundColor = "#cccccc";
divRed.innerHTML = 'Text';
div.appendChild(divRed);此外,文字Text用于消除字符大小的差异。
为什么它们不像预期的那样垂直排列?我遗漏了什么?
发布于 2014-10-09 23:42:51
在回顾了这个SO post之后,很明显,我对绝对定位的理解是错误的。通过设置父级上的绝对位置,我可以使用它的子级相对于父级的绝对位置。键是将位置设置为绝对值的父键!
var divGreen = document.createElement("div");
divGreen.style.position = "absolute";
divGreen.style.width = "10%";
divGreen.style.left = "100%";
divGreen.style.top = "37px";
divGreen.style.marginLeft = "-40%";
divGreen.style.color = "green";
divGreen.style.textAlign="left";
divGreen.style.backgroundColor = "#cccccc";
divGreen.innerHTML = 'Text';
div.appendChild(divGreen);
var divRed = document.createElement("div");
divRed.style.position = "absolute";
divRed.style.width = "10%";
divRed.style.left = "100%";
divGreen.style.top = "37px";
divRed.style.marginLeft = "-20%";
divRed.style.color = "red";
divRed.style.textAlign="left";
divRed.style.backgroundColor = "#cccccc";
divRed.innerHTML = 'Text';
div.appendChild(divRed);现在,我的链接按预期垂直对齐:

https://stackoverflow.com/questions/26285384
复制相似问题