Html 使用 float:left 时 CSS 背景消失

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9538247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:54:25  来源:igfitidea点击:

CSS background disappears when using float:left

htmlcsscss-float

提问by Upvote

This is my html:

这是我的 html:

<div class="header_wrapper">
       <div class="main_nav">
       <div>TEst</div>
       <div>TEst</div>
       <div>TEst</div>
    </div>
    <div class="clear"></div>
</div>

As you can see I want to build a menu with floating divs. Doing so the background of main_nav disappears.

如您所见,我想构建一个带有浮动 div 的菜单。这样做 main_nav 的背景消失了。

.header_wrapper{

    height:129px;
    background:url('images/layout/header.png') no-repeat #1f1f1f;
    border-bottom:1px solid #1f66ad
}

.header_wrapper .main_nav{
    position:relative;
    top:77px; left:336px;
    width:750px;
    background:red;
}

.header_wrapper .main_nav div{
    float:left;
}

.clear{
    clear:both;
}

I tried to use clear:both, however the background is still gone. Any ideas why?

我尝试使用 clear:both,但是背景仍然消失了。任何想法为什么?

回答by j08691

Adding overflow:auto;to main_nav brings the background back.

添加overflow:auto;到 main_nav 将背景带回来。

回答by animuson

This is because floated content does not take up any space. Your parent main_divdivision essentially takes on a height of 0 because it has no other content, which "hides" the background (there is no height to display behind).

这是因为浮动内容不占用任何空间。您的父main_div分区的高度基本上为 0,因为它没有其他内容,这“隐藏”了背景(后面没有显示高度)。

This information is available in the css-floating tag wikiand I've also posted other more detailed information about floating and parent containers.

此信息可在css-floating tag wiki 中找到,我还发布了有关浮动容器和父容器的其他更详细信息

回答by Sparky

Put overflowon .main_nav

overflow.main_nav

.header_wrapper .main_nav div{
    float:left;
    overflow: hidden;
}

Your clearing divforces its parent to expand, it has no effect on its sibling's background.

您的清算div迫使其父级扩展,它对其兄弟级的背景没有影响。

回答by sandeep

You have to clearto your float DIV's parent which is .main_nav. Write like this:

你必须到clearfloat DIV'的父母那里.main_nav。像这样写:

.header_wrapper .main_nav{
  overflow:hidden;
}