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

时间:2015-07-03 21:49:49

标签: css parent-child parent viewport

本周早些时候,我正在开设一个wepage,其中包含了#banner; image'正在根据浏览器和屏幕大小切断屏幕的视口。

我认为只需将父容器转换为'高度:100vh'这将使所有子元素都适合现在设置为适合任何视口高度的父容器。

这不像我预期的那样有效。 即使父容器设置为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 -->

1 个答案:

答案 0 :(得分:1)

  

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

100vh不是一个神奇的数字,它使所有其他元素都适合视口窗口。

如果您希望横幅图像与视口的高度相关,请以百分比形式设置高度,或者,因为您已经使用了视口单元,所以设置高度。

* {
  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计算元素维度...这一切都取决于您尝试做什么。