【问题标题】:% height does not work as I expected% 高度不像我预期的那样工作
【发布时间】:2016-03-07 20:38:22
【问题描述】:

我正在尝试创建一个响应式 div,它有一个部分和旁边。父 div 占据 25% 的高度。并且子 div 必须占据其父容器的 80%。但是如果高度以 % 为单位,它们就不会占据。但是当高度以像素为单位时,它可以正常工作。谁能告诉我哪里出错了。 这是html

<div class="container">

  <section>
    This is supposed to be a section
  </section>
  <aside>
    This is supposed to be aside

  </aside>

</div>


这是CSS

.container{
  width: 100%;
  background: red;
  height: 25%;
}

.container::before,
.container::after{
  content: "";
  display: table;

}

.container::after{
  clear: both;
}

section{
  float: left;
  width: 40%;
  height: 100%;
  display: block;
}

aside{
  float: right;
  width: 40%;
  height: 80%;
}

section, aside{
  background: green;
  border-radius: 6px;
  margin: 5%;
}

这是我的小提琴https://jsfiddle.net/gvpmahesh/Lhpv0k2x/3/

【问题讨论】:

标签: html css responsive-design


【解决方案1】:

你需要为body和html标签指定高度

https://jsfiddle.net/Lhpv0k2x/5/

body,html { height: 100%; }

编辑

我不是float的粉丝,但如果你需要使用它,你可以这样做:

https://jsfiddle.net/Lhpv0k2x/9/

我编辑:

  • .container 5% 的垂直填充(以避免元素中的垂直边距)
  • section, aside 水平边距仅为 5%

仅此而已

【讨论】:

  • 但是为什么即使我们应用了clearfix,浮动也脱离了父容器
  • 这就是空间,我可以编辑小提琴来展示如何修复
  • 您可以使用 clearfix 删除 div 标签。而且我不理解代码中的垂直填充,垂直对齐。你能解释一下吗?
  • 是的,clearfix 是一个测试,但这不是解决方案。使用容器中的填充,您可以分隔元素。如果你放置一个 100% 的高度和 5% 的边距(顶部和底部),总高度将是 110%,这是因为盒子超出了容器。
【解决方案2】:

您需要在父元素上应用position: relative; height: 100%;,即html 和body。

您还需要将position: relative; 应用于您想要使用 % height 的任何元素。

小提琴:https://jsfiddle.net/vdy82azk/

编辑: position: relative; 不是 每个 元素所必需的。 (查看这里的评论)

【讨论】:

  • 那不是真的 - 你不需要定义位置来使用基于百分比的高度,只是所有的父标签都需要定义一个高度,无论是百分比还是像素。 (例如,从小提琴中删除定位不会改变任何事情)
  • @somethinghere 是对的。 clearfix 没有破坏,只是明确定义了高度,内容恰好流出了容器。
【解决方案3】:

你需要这样写:

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

            }
.container{
  width: 100%;
  background: red;
  height: 25%;
}

.container::before,
.container::after{
  content: "";
  display: table;

}

.container::after{
  clear: both;
}

section{
  float: left;
  width: 40%;
  height: 80%;
  display: block;
}

aside{
  float: right;
  width: 40%;
  height: 80%;
}

section, aside{
  background: green;
  border-radius: 6px;
  margin:5%;
}

链接:

 https://jsfiddle.net/1utwx2fp/

【讨论】:

    猜你喜欢
    • 2012-06-13
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2022-01-11
    • 2012-07-13
    • 1970-01-01
    相关资源
    最近更新 更多