为什么必须浮动:右边是“正常”的左对齐div?

时间:2011-09-06 16:49:13

标签: html css-float

<html>
<head>
   <style type="text/css">
      div, p {border: 1px dashed;}
   </style>
</head>
<body>

<!-- Why must the text that's intended to be right-justified *PRECEED*
   the text that is to be left-justified? It "feels" like the syntax should
   simply read from top to bottom:

   <div>
   "Put some text here"
   "Then put some text here, but align it right"
   </div>

   Instead, this seems to work:
   <div>
   "The right-justified text has to go first"
   "Then we code the 'normal' left-justified text"
   </div>

   I see how to 'make it work', but I'm curious as to the logic behind this
   seemingly 'backwards' syntax.  What am I misunderstanding?
-->

<div>

   <!-- Does NOT work as intended -->
   <div>
      <p>I am on the Left</p>
   </div>

   <div style="float: right;">
      <p>I am on the RIGHT, but I don't align</p>
   </div>


   <br />
   <br />
   <br />


   <!-- Works as intended -->
   <div style="float: right;">
      <p >I am on the RIGHT, and I mostly align</p>
   </div>

   <div>
      <p class="">I am on the Left</p>
   </div>


</div>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

很难关注您的问题,因为您混合了justifyfloat这两个词。文本可以左右对齐,div不能。它们只能浮动。

除此之外,您的问题的答案与文档流程有关。我认为你所期待的是你将正确浮动的div放在正常浮动的div之后它们并排结束。也就是说,您希望右浮动div“知道”您希望它与文档流中位于其上方的div并排。

但为什么要知道呢?

也许你的意思是它与一个div并排进一步向上或向下。如你所见,它有点武断。如果上面的没有 div要浮动到旁边会发生什么呢?

相反,组合CSS的人决定div将从文档float中出现的任何位置水平浮动,在此时退出流程。因此,通过将右浮动div放在普通div之上,你会告诉它从文档中的那一点浮动,其他一切“向上移动”。

这有帮助吗?