本周早些时候,我正在处理一个网页,根据浏览器和屏幕大小,“横幅图像”被截断了屏幕的视口(viewport)。
我认为通过简单地将父容器转换为“高度:100vh”,这将使所有子元素适合现在设置为适合任何视口(viewport)高度的父容器。
这并没有像我预期的那样工作。 即使父容器设置为 100vh,横幅图像仍被截断。
有办法吗?
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>
替代布局方法可能更适合您,例如 flexbox
或使用 calc
计算元素尺寸...这完全取决于您要做什么。
关于css - 获取子元素以尊重父元素的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31214564/