【问题标题】:should floated divs have height浮动的div应该有高度
【发布时间】:2013-09-20 09:36:21
【问题描述】:

我是 CSS 和 HTML 的新手,我对浮动元素的高度有一个问题:

当我将“内容”div 的高度设置为大于或等于“主”div 高度时,页脚的边距顶部显示正确,但只要我将内容 div 的高度更改为自动,页脚顶部的边距不起作用。我真的很想知道是否有任何解决方案可以使内容高度自动但尊重页脚的边距顶部。请帮我。我已经尝试了所有方法:各种清除修复、溢出等。

<div id="container">
    <div id="header"></div>
    <div id="content">
        <div id="sidebar"></div>
        <div id="main"></div>
    </div>
    <div id="footer"></div>
</div>

#container { width:800px; height:auto; background:#000; }
#header { width:800px; height:80px; background:#333; }
#content { width:800px; height:500px; background:#999; }
#main { width:600px; height:500px; background:skyblue; float:right; }
#sidebar { width:200px; height:500px; background:silver; float:left; }
#footer { width:800px; height:80px; background:green; clear:both; margin-top:10px; }

【问题讨论】:

标签: html css


【解决方案1】:

使用overflow:hidden 属性。

“溢出:隐藏”通常用于浮动遏制。 但是,它可以做更多特殊的事情:防止元素的边距 避免与其子元素折叠并防止元素 在相邻的浮动元素“后面”扩展。

来源:The magic of “overflow: hidden”

#content{
    width:800px;
    height:auto;
    background:#999;
    overflow:hidden;
}

see jsFiddle

【讨论】:

  • 感谢它的工作,它非常有帮助,我实际上使用了溢出:自动;因为我需要在必要时滚动内容,但它仍然有效,
【解决方案2】:

快速修复...这是Fiddle

#container{width:800px;height:auto;background:#000;}
#header{position:relative;width:800px;height:80px;background:#333;}
#content{position:relative;width:800px;height:500px;background:#999;}
#main{position:relative;width:600px;height:800px;background:skyblue;float:right;margin-bottom: 10px;}
#sidebar{position:relative;width:200px;height:800px;background:silver;float:left;margin-bottom: 10px;}
#footer{position:relative;width:800px;height:80px;background:green;clear:both;}

【讨论】:

  • 感谢您的回答,但您已向主和侧边栏 div 添加边距,这正是我现在所做的,但我想在页脚添加边距而不向其他 div 添加任何底部边距。
【解决方案3】:

您设置的问题在于,当您将#containerheight 设置为auto 时,它的高度实际上被计算为零。这是因为#container 包含纯浮动元素,在计算#container 的高度时会忽略它们。

要解决此问题,请在 #content 内添加一个 clearfix,但在任何其他内容之后。例如:

<div id="content">
    <div id="sidebar"></div>
    <div id="main"></div>
    <div class="clearfix"></div>
</div>

CSS:

.clearfix { clear: both }

你可以在这里看到它的工作原理:http://jsfiddle.net/Mzxjs/

【讨论】:

    猜你喜欢
    • 2013-10-06
    • 2013-06-27
    • 2023-03-08
    • 2012-02-22
    • 2014-03-21
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多