使用float时Div折叠 [英] Div collapse when using float

查看:121
本文介绍了使用float时Div折叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML,我想在按钮和文本后面显示一个蓝色背景。不幸的是,使用以下代码,蓝色背景消失。如果我删除ids按钮和文本的CSS,背景是回来的。

I have the following HTML and I would like to display a blue background behind the buttons and text. Unfortunately, with the following code, the blue background disappear. If I remove the CSS for the ids buttons and text, the background is back.

我做错了什么?

谢谢!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
    <style>


    #actions
    {
        background: blue;
    }

    #buttons
    {
        float: left;
    }

    #text 
    {
        float: right;
    }

    </style>
</head>
<body>

        <div id="actions">
            <div id="buttons">
                <input type="button" id="btnOne" value="Bla bla" />
                <input type="button" id="btnTwo" value="Bla bla bls" />
            </div>
            <div id="text">Bla bla bla</div>
        </div>

</body>
</html>


推荐答案

浮动元素使它们脱离页面的正常块定位,因此右浮动的元素突破父容器,折叠div。你可以清除它们,或者更简洁和聪明的方法是添加overflow:auto到父容器:

You have to "clear" your floats. Floating elements takes them out of the normal block positioning of the page, so an element that is floated right breaks out of the parent container, collapsing the div. You can clear them, or the more concise and clever way is to add 'overflow: auto' to the parent container:

#actions
{
    background: blue; overflow: auto;
}

#buttons
{
    float: left;
    overflow: hidden;
}

#text 
{
    float: right;
    overflow: hidden;
}

由于overflow:auto可以在某些情况下产生滚动条通过在children元素上指定overflow:hidden来防止这种情况。这在我的经验中可靠地工作。

Since "overflow: auto" can produce scrollbars in certain instances, I usually explicitly prevent that by specifying 'overflow: hidden' on children elements. This works reliably in my experience.

这篇关于使用float时Div折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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