【问题标题】:Child elements are not contained in viewport height even if parent's height is set to be `100vh` [duplicate]即使父元素的高度设置为“100vh”,子元素也不包含在视口高度中[重复]
【发布时间】:2020-12-27 23:56:20
【问题描述】:

.parent{
  background: #64B5F6;
  height: 100vh;
  display: grid;
  grid-template-columns: 40% 60%;
}

.child1 {
  background: #42A5F5;
  height: 100%;
}

.child2{
  background: #FFEB3B;
  height: 100%;
}

.img1 {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.img2 {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class='parent'>
  <div class='child1'>
    <img class='img1'src="https://images.unsplash.com/photo-1597594879431-8aecf7c2dd49?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ" alt="man image">
  </div>
  <div class='child2'>
    <img class='img2'src="https://images.unsplash.com/photo-1598505628759-67b9346af31c?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ" alt="man image">
  </div>
</div>

在上面的代码中,我将父级的height 设置为100vh。这意味着它应该包含在视口的高度中。但是它的子元素正在扩展这个高度。我在 codepen.io 中运行了这个,发现父级现在不是视口的height,而是更多。我不知道我在这里做错了什么。

【问题讨论】:

  • 我刚刚使用开发工具查看了.parent 及其子元素的尺寸,它们具有相同的高度。也许你想知道为什么会有垂直滚动条?
  • @Yousaf 高度将相同,但由于我已将父级高度设置为100vh,因此不应扩展视口高度。但他们正在扩展视口高度。
  • 是的,子元素的高度与父元素的高度相同。我不确定你对什么感到困惑。要移除垂直滚动条,请移除 body 元素上的边距。 body { margin: 0 };
  • @Yousaf 我重新构建了这个问题以便更好地理解。你现在能看到吗?

标签: html css flexbox grid


【解决方案1】:

所有错误在于body 元素的默认边距为 8 像素,因此这是在高度上增加了 16 像素。

要修复 ie,您只需将边距设置为 0,因此将其添加到 CSS 的开头:

body { margin:0;}

工作示例:

body { margin:0;}

.parent{
  background: #64B5F6;
  height: 100vh;
  display: grid;
  grid-template-columns: 40% 60%;
}

.child1 {
  background: #42A5F5;
  height: 100%;
}

.child2{
  background: #FFEB3B;
  height: 100%;
}

.img1 {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.img2 {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class='parent'>
  <div class='child1'>
    <img class='img1'src="https://images.unsplash.com/photo-1597594879431-8aecf7c2dd49?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ" alt="man image">
  </div>
  <div class='child2'>
    <img class='img2'src="https://images.unsplash.com/photo-1598505628759-67b9346af31c?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ" alt="man image">
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多