为什么两个块需要浮动左为了对齐? [英] Why two blocks need to be floated left in order to be aligned?

查看:219
本文介绍了为什么两个块需要浮动左为了对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个HTML:

​<div class = "block1">hi</div>
<div class = "block2">hi</div>

此CSS:

​.block1 {
    width:100px;
    border:1px solid;
    float: left;
}

​.block2 {
    width:100px;
    border:1px solid;
}

为什么block2需要 float:left; 为了在block1的右边?是不是block1的属性(float:left)够了?

Why does block2 need to have float:left; in order to be to the right of block1? Isn't the property of block1 (float:left) enough?

JsFiddle

推荐答案

block2 level元素,这意味着它占用了一整行。

block2 is displayed as a block level element by default, which means it takes up a whole line.

它不一定需要 float:left 才能显示在 block1 ;如果它通过 display:inline display:inline-block 显示为内联级元素,旁边的兄弟姐妹。

It doesn't necessarily have to have float:left to show up on the right of block1; if it is displayed as an inline level element through display:inline, or display:inline-block, it will appear next to its sibling.

http:// jsfiddle。 net / 8GF4B / 1 /

更详细的解释一下,让我们想像你设置了 float:left block2 代替:

To explain it in further detail, let us imagine you had set float:left on block2 instead:

.block1 {
    width:100px;
    border:1px solid;
}

​.block2 {
    width:100px;
    border:1px solid;
    float: left;
}

发生的第一件事是block2将被放置在正常位置定位。让我们找出哪里。

The first thing that will happen is that block2 will be positioned where it would normally be positioned. Let's find out where.


  • block1显示为块级元素

  • 在元素

  • 之前和之后都有换行符。因此,block2将默认显示在第二行

现在block2从正常流中取出,并向左移动,因为它可能是...但它已经在左边缘了!这会导致block2显示在block1下面。

Now block2 is taken out of the normal flow, and shifted as far left as it can possibly be ... but it is already against the left edge! This results in block2 showing up underneath block1.

这里有一个很好的解释内联和块级元素之间的区别: https://developer.mozilla.org/en-US/docs/HTML/Block-level_elements

Have a look here for a good explanation of the distinction between inline and block-level elements: https://developer.mozilla.org/en-US/docs/HTML/Block-level_elements

这篇关于为什么两个块需要浮动左为了对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆