CSS 为什么我不能将元素与 display: block 和 width: X 右对齐?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10490639/
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-30 03:48:00  来源:igfitidea点击:

Why can I not right-align an element with display: block and width: X?

csslayouttext-alignment

提问by Dan Tao

Total n00b question here (at least to the CSS elite):

这里共有 n00b 问题(至少对 CSS 精英而言):

Why is it that an element with both display: block;and a value for widthdoes not seem to fall in line with the text-alignproperty of its parent? That is, it always seems to insist on keeping to the left.

为什么同时具有display: block;和 值的元素width似乎不符合text-align其父级的属性?也就是说,它似乎总是坚持保持在左边。

Here is a jsFiddle illustrating the issue.

这是一个 jsFiddle 说明了这个问题。

Obviously, this must be consistent with the CSS spec (I mean, if Chrome, Firefox and Opera all agree on it, I have very little doubt); I just don't really get it.

显然,这必须符合 CSS 规范(我的意思是,如果 Chrome、Firefox 和 Opera 都同意,我几乎没有怀疑);我只是不明白。

回答by michaelward82

The text is aligned right inside a 150px box. That is correct. A block element will not align to text-align in the parent.

文本在 150 像素的框内对齐。那是正确的。块元素不会与父元素中的 text-align 对齐。

To fix this you need to use either display: inline-blockor float: righton the .width div.

要解决此问题,您需要在 .width div 上使用display: inline-blockfloat: right

edit: with float, add clear: rightto avoid it being on the same line as the previous div

编辑:使用浮动,添加clear: right以避免它与前一个 div 在同一行

回答by Ken W

It's because your class is block width not width. Rename the class block_width and then in your css make the last one .block_width rather than the .width you have and it works

这是因为您的类是块宽度而不是宽度。重命名类 block_width 然后在你的 css 中创建最后一个 .block_width 而不是你拥有的 .width 并且它可以工作

回答by Oswaldo Acauan

<span>is an element with display: inline. Elements with display: inlinefollowing the text alignment. Elements with display: blockdoes not follow the alignment of text are aligned OWNED by the float.

<span>是一个带有 的元素display: inlinedisplay: inline跟随文本对齐的元素。display: block不跟随文本对齐的元素被浮动对齐。

When you just change the width of the element remains inline, following the alignment of text, but when you change your display to block and change its width, its content assumes the alignment of text, but the element does not. I tried to illustrate this with some color in your code ;)

当您仅更改元素的宽度时,它保持内联,跟随文本对齐,但是当您将显示更改为块并更改其宽度时,其内容假定文本对齐,但元素不会。我试图在你的代码中用一些颜色来说明这一点;)

http://jsfiddle.net/Z6Twf/3/

http://jsfiddle.net/Z6Twf/3/

回答by anson

alternative way

替代方式

<div style="text-align:right; margin:0px auto 0px auto;">
<p> Hello </p>
</div>
  <div style="">
<p> Hello </p>
</div>