两个块级元素;为什么我需要float两者并排放置? [英] Two block-level elements; why do I need float on both to position them side by side?

查看:147
本文介绍了两个块级元素;为什么我需要float两者并排放置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个关于浮动的一个非常基本的问题,但我不能找到一个搜索引擎的答案。

This is a very basic question about floats but I couldn't find an answer with search engines.

当我有两个块级元素)和我需要他们彼此相邻,为什么不够的给他们的第一个float:left -property?为什么我需要浮动两个div,将第二个放在第一个而不是下面呢?

When I have two block-level elements (divs for example) and I need them next to each other, why is it not enough to give the first one of them the float:left -property? Why do I need to float both of the divs to put the second next to the first instead of below it?

这里是一个代码示例:

<div id="box_wrap">
    <div id="box1">
        <h2>Box1 text</h2>
        <p>Lorem Ipsum</p>
    </div>
    <div id="box2">
        <h2>Box2 text</h2>
        <p>Lorem Ipsum</p>
        <p>Text</p>
    </div>

</div>



CSS



CSS

#box1 {
    background-color: blue;
    width: 30%;
    float: left;
}

#box2 {
    background-color: red;
    width: 30%;
    float: left;
}


推荐答案

流,并且悬浮在#box2 的内容,而不是div本身。本质上没有足够的空间。如果你给#box2 60%的宽度,你可以看到这一点。

Floats are removed from normal document flow, and is floated left of the contents of #box2, but not the div itself. In essence there isn't enough room. You can see this if you give #box2 a 60% width.

第二个框它自己的块格式化上下文。执行此操作的一个属性是设置 overflow:hidden

You can change this behavior by giving the second box its own block formatting context. One property that does this is setting overflow: hidden

#box2 {
    background-color: red;
    width: 30%;
    overflow: hidden;
}

演示 http://jsfiddle.net/7tmmk/2/

其他方式给予元素自己块格式化上下文: https://developer.mozilla.org/en-US/ docs / CSS / Block_formatting_context

For other ways of giving an element its own block formatting context see: https://developer.mozilla.org/en-US/docs/CSS/Block_formatting_context

有关此和其他事情的更多信息 overflow:hidden 请查看 http://colinaarts.com/ articles / the-magic-of-overflow-hidden /#making-room-for-floats

For more information on this and other things overflow: hidden does, check out http://colinaarts.com/articles/the-magic-of-overflow-hidden/#making-room-for-floats

这篇关于两个块级元素;为什么我需要float两者并排放置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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