且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取子元素以尊重父元素Width&高度

更新时间:2023-10-08 10:13:22


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

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 并不是使所有其他元素都适合视口窗口的神奇数字。

100vh is not a magic number that makes all other elements fit into the viewport window.

如果您希望横幅图像与视口的高度相关,请以百分比或视口单位为单位设置高度。

If you want your banner image to be related to the height of the viewport, set a height either in percentage or, since you are already using then, viewport units.

* {
  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演示

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

Alternative layout methods might suit you better such as flexbox or calculating element dimensions using calc...it all depends on what it is you are trying to do.