css - text-align 会将内部元素向右移动,但如果指定了宽度则不会?

标签 css

我敢肯定这是一件非常简单的事情,但我一整天都在苦苦思索,所以我决定问问。

我有一些 div,我想在它们的父 div 中向右对齐。如果我没有指定宽度,“text-align: right”会起作用:

<div style="text-align: right;">
    <div>
        This text aligns to the right
    </div>
</div>

但是如果我在内部元素上放置一个以像素为单位的大小,它不会:

<div style="text-align: right;">
    <div style="width: 200px;">
        This div stays on the left
    </div>
</div>

我错过了什么?

最佳答案

实际上,text-align 会影响包括文本在内的内联元素。

来自 MDN

The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content.

在第一种情况下,内部 div 继承了外部 divtext-align 属性并将其应用于其内联元素,

即内部 div 本身没有向右或向左对齐。但当它填满其父级的整个水平空间时,您会看到文本在外部 div 的右侧对齐。

在第二种情况下,内部 div 有一个明确的 width 并且它不再填充其父级的整个水平空间,并且 text -align 应用于文本而不是 div 本身。

如果你想把内层的div移到一边。您有两个选择:

  1. 对内部使用 float: right 并清除外部 div 末尾的 float 。 <强> Working Demo

  2. 对内部使用 display: inline-block,对外部 div 使用 text-align: right
    <强> Working Demo .

关于css - text-align 会将内部元素向右移动,但如果指定了宽度则不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22236490/

相关文章:

html - z-index 在课后不工作

html - CSS "hover"显示奇怪的字符

html - CSS-Grid:如何将 2 个左对齐,一个大的在中间,两个右对齐?

html - 使按钮变大,但保持文本大小不变

html - 新的BFC "clearing" float 框

jquery - HTML 将鼠标悬停在图像上方的图像滚动出来

css - Twitter BootStrap - 边框下推内容

javascript - 如何学习创建日期选择器

css - 移动 safari 的硬件加速 CSS 属性列表

javascript - 使用 VBA 将数组传入和传出网页中的脚本函数