请观察这个简单的jsFiddle:http://jsfiddle.net/mark69_fnd/vtLrt/10/
HTML:
<div class="char">
<div>
<div class="char">A1</div>
<div class="char anchorToMiddle">D1</div>
<div class="char anchorToRight">G1</div>
</div>
<div>
<div class="char">A2</div>
<div class="char anchorToMiddle">D2</div>
<div class="char anchorToRight">G2</div>
</div>
<div>
<div class="char">A3</div>
<div class="char">B3</div>
<div class="char">C3</div>
<div class="char">D3</div>
<div class="char">E3</div>
<div class="char">F3</div>
<div class="char">G3</div>
</div>
</div>
CSS:
.char{
display: inline-block;
}
.anchorToRight {
float: right;
}
输出:
如何更改HTML和/或CSS,以便标记为anchorToMiddle
(D1和D2)的元素在D3的正上方对齐?
感谢。
答案 0 :(得分:2)
我试图找到一些带有javascript的解决方案(因为问题是用javascript标记的)。
如果在“anchorToMiddle”中将text-align设置为“center”,则文本将居中,但仅当您指定元素的宽度时。为此,B3..F3包含在另一个div中(id为“charspan”):
<div id="charspan" class="char">
<div class="char">B3</div>
<!-- etc. -->
</div>
然后计算这个新div的宽度并应用于“anchorToMiddle”类。
var elems, i, width, span;
elems = document.getElementsByClassName("anchorToMiddle");
span = document.getElementById("charspan");
width = parseInt(window.getComputedStyle(span).width);
for (i = 0; i < elems.length; i++) {
elems[i].style.width = width + 'px';
}
答案 1 :(得分:1)
如果你给它一个合适的宽度,然后使用text-align:center;
属性,它应该得到修复。
我已更新您的FIDDLE
答案 2 :(得分:0)
div.anchorToMiddle
{
width:someWidthValue less than parent;
margin-left:auto;
margin-right:auto;
}
答案 3 :(得分:0)
为什么不改用3x7表呢?
<table>
<tr>
<td>A1</td>
<td> </td>
<td> </td>
<td>D1</td>
<td> </td>
<td> </td>
<td>G1</td>
</tr>
<tr>
<td>A2</td>
<td> </td>
<td> </td>
<td>D2</td>
<td> </td>
<td> </td>
<td>G2</td>
</tr>
<tr>
<td>A3</td>
<td>B3</td>
<td>C3</td>
<td>D3</td>
<td>E3</td>
<td>F3</td>
<td>G3</td>
</tr>
</table>