Html 文本对齐:右;不适用于 <label>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9101507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:13:19  来源:igfitidea点击:

text-align: right; not working for <label>

htmlcssformslabelalignment

提问by Ilja

Simply enough I can't get text to align to right in a <label>element.

很简单,我无法让文本在<label>元素中右对齐。

HTML

HTML

<div id="contact_form">
 <label for="name" id="name_label">Name:</label>
 </div>

CSS

CSS

#contact_form label {
  text-align: right;
}

My page: http://freshbeer.lv/development/en/contact.php

我的页面:http: //freshbeer.lv/development/en/contact.php

You can see labels for name, phone, email etc... are aligned to the left, but I need them to be aligned to the right, so could anyone please suggest something?

您可以看到姓名、电话、电子邮件等标签...左对齐,但我需要它们右对齐,所以有人可以提出建议吗?

回答by janhartmann

Labelis an inline element - so, unless a width is defined, its width is exact the same which the letters span. Your divelement is a block element so its width is by default 100%.

Label是一个内联元素 - 因此,除非定义了宽度,否则它的宽度与字母跨度完全相同。您的div元素是块元素,因此其宽度默认为 100%。

You will have to place the text-align: right;on the divelement in your case, or applying display: block;to your label

您必须将 放在您的案例中text-align: right;div元素上,或应用于display: block;您的label

Another option is to set a width for each label and then use text-align. The display: blockmethod will not be necessary using this.

另一种选择是为每个标签设置一个宽度,然后使用text-align. display: block使用此方法将不需要该方法。

回答by Gui Premonsa

You can make a text align to the right inside of any element, including labels.

您可以使文本与任何元素(包括标签)的右侧对齐。

Html:

网址:

<label>Text</label>

Css:

css:

label {display:block; width:x; height:y; text-align:right;}

This way, you give a width and height to your label and make any text inside of it align to the right.

通过这种方式,您可以为标签指定宽度和高度,并使其中的任何文本向右对齐。

回答by mfnx

As stated in other answers, label is an inline element. However, you can apply display: inline-blockto the label and then center with text-align.

正如其他答案中所述,标签是一个内联元素。但是,您可以应用display: inline-block到标签,然后以 为中心text-align

#name_label {
    display: inline-block;
    width: 90%;
    text-align: right;
}

Why display: inline-blockand not display: inline? For the same reason that you can't align label, it's inline.

为什么display: inline-blockdisplay: inline?出于同样的原因,你不能 align label,它是内联的。

Why display: inline-blockand not display: block? You could use display: block, but it will be on another line. display: inline-blockcombines the properties of inlineand block. It's inline, but you can also give it a width, height, and align it.

为什么display: inline-blockdisplay: block?您可以使用display: block,但它会在另一行上。display: inline-block结合了inline和的属性block。它是内联的,但你也可以给它一个宽度、高度和对齐它。