我有一个外部“容器” div,我想在其中放置内部div,该内部div包含垂直和水平居中的文本(以“ p”元素的形式)。看起来像这样:
蓝色部分:外部容器部分
绿色:“内部div”,如您所见,其黑色文本实际上在垂直和水平居中。
我通过相对定位实现了这一点:
<div class="container" id="c">
<div id="node1" class="node" style="position: relative; top: 50px; left: 50px;"><p class="numtext" id="node1text">1</p></div>
<div id="node2" class="node" style="position: relative; top: 100px; left: 100px;"><p class="numtext" id="node2text">2</p></div>
<div id="node3" class="node" style="position: relative; top: 150px; left: 150px;"><p class="numtext" id="node3text">3</p></div>
</div>
我使用的CSS的相关部分如下:
div.container {
margin-left: auto;
margin-right: auto;
position:relative;
overflow-y: auto;
}
div.node {
border-radius: 50%;
text-align: center;
}
p.numtext {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
line-height:100%; /* This vertically centers the text in the parent div, found on stackoverflow */
}
So far, so good. However, the problem is that if I remove the middle "2" node, the position of the "3" node also changes! (Likewise, if I remove the "1" node, the positions of the other 2 change.) It moves up and to the left slightly, but not all the way to where 2 was before. See picture:
Yet, everything else in the code is the EXACT SAME! So I assumed relative positioning had something to do with it, and I was right; if I changed that (for instance, the div lines would now read like:)
<div id="node1" class="node" style="position: absolute; top: 50px; left: 50px;"><p class="numtext" id="node1text">1</p></div>
I get something very different looking:
This, actually, looks closer to what the code "should" output, because the nodes are only separated by a small distance that looks more like 50 pixels (for reference, the size of each node is 75.6px). But, obviously, the vertical alignment of the text is WAY out of whack, and for good reason - the nodes [green] are now positioned absolutely, so the text, which is positioned "relatively," is now positioned relative to the container [light blue], not the node (I don't think I explained that properly, but what I'm referring to is similar to this case, I think: Absolute positioning inside absolute position).
因此,我想我需要保持所有三个元素(外部div,内部div和内部文本)的相对位置,但是我不知道如何使内部div的位置彼此独立。有什么想法吗?
我也喜欢放弃相对定位的想法,并且绝对将内部div和文本都定位,但是我仍然需要将文本置于绿色圆圈的中心(但是请注意,圆圈也可以改变大小[和文本以及它们),并且该文本可能有多个数字,也许以后我甚至想切换到其他字体,因此确保垂直对齐似乎是一个困难的问题)。
如果我错了,请纠正我,但这不是您要尝试做的吗?
.container {
position: relative;
width: 300px; /* for demo only */
margin: 0 auto;
}
.circle {
position: absolute;
width: 60px; /* whatever your circle size */
line-height: 60px; /* whatever your circle size */
text-align: center;
border-radius: 50%;
background: #a0f4b6;
}
.circle-1 {
top: 50px;
left: 50px;
}
.circle-2 {
top: 100px;
left: 100px;
}
.circle-3 {
top: 150px;
left: 150px;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句