【问题标题】:Confusion with height:auto [duplicate]与高度混淆:自动[重复]
【发布时间】:2015-04-24 20:50:57
【问题描述】:

在以下场景中,我不明白为什么元素 wrappercontent 的高度设置不正确,即使它们设置为 height: auto,这意味着没有显示带有类 wrap 的 2 个 div在包装器和内容 div 中。

我在这个 JSfiddle 中重现了这个问题:

http://jsfiddle.net/202oy3k8/

正如您所见,两个橙色 div 并未显示在包装 div 内,即使包装高度设置为自动。是什么导致了这个问题,我该如何解决?

HTML 代码:

<div id="wrapper">
    <div id="content">
        <div id="top">

        </div>
        <div class="dash"></div>
        <p id="header">Header</p>

        <div class="wrap">
        </div>
        <div class="wrap">
        </div>
    </div>
</div

CSS 代码:

html, body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

#wrapper {
    background-color: black;
    margin-top: 2%;
    width: 100%;
    height: auto;
}

#content {
    background-color: green;
    width: 1224px;
    height: auto;
    margin: auto;
    text-align: center;    
}

#top {
    background-color: pink;
    height: 400px;
    width: 60%;
    margin: auto;
}

.dash {
    width: 80%;
    margin: auto;
    margin-bottom: 1%;
    height: 2px;
    background-color: black;
}

p#header {
    margin: 0;
    text-align: center;
}

.wrap {
    background-color: orange;
    margin: 1%;
    float:left;
    width: 48%;
    height: 400px;
}

【问题讨论】:

标签: html css


【解决方案1】:

您必须添加一个clear 属性来清除您已应用于.wrap div 的左浮动。

float 和 clear 有什么用?

如果您查看一本典型的杂志,您会看到说明 文章,文字在它们周围流动。 CSS中的float属性 创建是为了允许在网页上使用这种样式的布局。浮动 图像——或与此相关的任何其他元素——将它推到一边,然后 让文本在另一边流动。清除浮动元素意味着 如有必要,将其向下推,以防止它出现在旁边 浮子。尽管浮动旨在与任何元素一起使用, 设计师最常使用它来实现多列布局 无需滥用表格标记。

html,
body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}
#wrapper {
  background-color: black;
  margin-top: 2%;
  width: 100%;
  height: auto;
}
#content {
  background-color: green;
  width: 400px;
  height: auto;
  margin: auto;
  text-align: center;
}
#top {
  background-color: pink;
  height: 400px;
  width: 60%;
  margin: auto;
}
.dash {
  width: 80%;
  margin: auto;
  margin-bottom: 1%;
  height: 2px;
  background-color: black;
}
p#header {
  margin: 0;
  text-align: center;
}
.wrap {
  background-color: orange;
  margin: 1%;
  float: left;
  width: 48%;
  height: 400px;
}
.clear {
  clear: left;
}
<div id="wrapper">
  <div id="content">
    <div id="top"></div>
    <div class="dash"></div>
    <p id="header">Header</p>
    <div class="wrap"></div>
    <div class="wrap"></div>
    <div class="clear"></div>
  </div>
  </div

参考:w3.org - Floats and clearing - CSS-Tricks - What is "Float"?

【讨论】:

    猜你喜欢
    • 2012-12-16
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 2012-11-15
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多