css - 获取子元素以尊重父元素的宽度和高度

标签 css parent-child parent viewport

本周早些时候,我正在处理一个网页,根据浏览器和屏幕大小,“横幅图像”被截断了屏幕的视口(viewport)。

我认为通过简单地将父容器转换为“高度:100vh”,这将使所有子元素适合现在设置为适合任何视口(viewport)高度的父容器。

这并没有像我预期的那样工作。 即使父容器设置为 100vh,横幅图像仍被截断。

有办法吗?

JSFiddle Link

CSS

.parent {
    width: 100%;
    background-color: blue;
   border: 1px dashed blue;
    text-align: center;
}

.child-header {
    background-color: rgba(122, 234, 221, .4);
    width: 100%;
    background-color: gray;
    position: relative;
}

p {
    color: white;
    font-family: sans-serif;
    text-align: center;
}

h1 {
    color: white;
    text-align: center;
    font-family: sans-serif;
}

.banner-image {
    background-color: black;
    width: 80%;
    min-height: 500px;
    position: relative;
    margin: 0 auto;
}

HTML

<div class="parent"><!-- Wrapper Parent Container -->

    <div class="child-header">
        <p>Cool header with a nav will go here</p>
    </div>

    <h1>Some Headline Tag Here</h1>

    <div class="banner-image">
    </div>

    <h2>Blah Blah Blah...</h2>


</div><!-- End Wrapper -->

最佳答案

I thought that by simply converting the Parent Container to 'Height: 100vh' this would make all child elements fit within the parent container that is now set to fit the height of any viewport.

100vh 不是使所有其他元素适合视口(viewport)窗口的神奇数字。

如果您希望您的横幅图片与视口(viewport)的高度相关,请以百分比或视口(viewport)单位(因为您已经在使用)设置高度。

* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
.parent {
  background-color: blue;
  border: 1px dashed blue;
  text-align: center;
  min-height: 100vh;
}
.child-header {
  background-color: rgba(122, 234, 221, .4);
  background-color: gray;
  position: relative;
}
p {
  color: white;
  font-family: sans-serif;
  text-align: center;
}
h1 {
  color: white;
  text-align: center;
  font-family: sans-serif;
}
.banner-image {
  background-color: black;
  width: 80%;
  min-height: 50vh;
  position: relative;
  margin: 0 auto;
}
<div class="parent">
  <!-- Wrapper Parent Container -->
  <div class="child-header">
    <p>Cool header with a nav will go here</p>
  </div>
  <h1>Some Headline Tag Here</h1>

  <div class="banner-image"></div>
  <h2>Blah Blah Blah...</h2>

</div>

Jsfiddle Demo

替代布局方法可能更适合您,例如 flexbox 或使用 calc 计算元素尺寸...这完全取决于您要做什么。

关于css - 获取子元素以尊重父元素的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31214564/

相关文章:

html - 使用 CSS 创建响应式倾斜背景

c# - Ninject:将父实例提供给正在解析的子实例

C Minishell - 管道实现需要杀僵尸

database - 迁移 CoreData 中的实体父级

c# - 如何从页面级别获取父框架?

jquery - Parent.location.assign(url) 无法在 fancybox iframe 中工作

javascript - 当鼠标悬停在该行的任意位置时,我可以使 TableRow 列中的图标改变颜色吗?

html - 在表格单元格中将图标右对齐?

python - 检查整个 block 是否有任何带有内部文本的 child

html - 子菜单单击不适用于操作