我有一个问题,我很想通过使用 CSS 来解决,而不是诉诸于静态调整标签的大小(但也许这是不可能的)。
我每行有两个标签,一个用于显示“标题”,另一个用于显示关联的“值”。这是我希望的样子:
这类似于 Align labels in form next to input但我希望每行的第二个元素左对齐而不是第一个元素右对齐。我尝试修改该问题的已接受答案并设置“标题”标签的宽度,但这对我的输出没有影响。正如我上面提到的,无论如何我宁愿不对宽度进行硬编码,但我希望在尝试找到一个可以解释更大“标题”值的良好、长期的解决方案之前先得到一些东西。
这是我当前的 CSS(这些类应该是不言自明的):
.propertyTitle {
text-transform: uppercase;
width: 300px;/*Why doesn't this have any effect?*/
}
.propertyValue {
text-align: left;
}
还有我当前的 HTML:
<div>
<div>
<label class="propertyTitle">Hello:</label>
<label class="propertyValue">World</label>
</div>
<div>
<label class="propertyTitle">Goodbye:</label>
<label class="propertyValue">To All of the People in the World</label>
</div>
<div>
<label class="propertyTitle">I Want:</label>
<label class="propertyValue">These labels to line up</label>
</div>
</div>
HTML 也可以修改,如果这样更容易的话。为了符合最佳实践,我宁愿不使用表格来完成这项工作。
这是一个 jsFiddle显示我现在拥有的,我缺少什么?理想情况下,此解决方案适用于 IE8+ 和 Firefox,因此不幸的是,不鼓励使用 HTML5 和 CSS3 元素。
编辑
在前两个答案出现(都解决了我的问题)后重申一下,有没有一种方法可以在不对“标题”标签的宽度进行硬编码的情况下做到这一点?
最佳答案
像这样对你的 div 和标签进行分组:
<div>
<div class="titleWrap">
<label class="propertyTitle">Hello:</label>
<label class="propertyTitle">Goodbye:</label>
<label class="propertyTitle">I Want:</label>
</div>
<div class="valueWrap">
<label class="propertyValue">World</label>
<label class="propertyValue">To All of the People in the World</label>
<label class="propertyValue">These labels to line up</label>
</div>
</div>
使用以下 CSS:
.propertyTitle {
display:block;
text-transform: uppercase;
width: auto;
}
.titleWrap{
display:inline-block;
}
.propertyValue {
display:block;
width:auto;
}
.valueWrap {
display:inline-block;
}
无需指定宽度即可为您提供所需的结果
看看这个 jsFiddle
关于html - 使用 CSS 水平对齐标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22256911/