我本周初在一个网页上工作,其中“横幅图像”被截断了屏幕的视口,具体取决于浏览器和屏幕的大小。
我认为,只需将“父容器”转换为“高度: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 -->
最佳答案
我认为,只需将“父容器”转换为“高度: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
计算元素尺寸...这完全取决于您要执行的操作。关于css - 获取子元素以尊重父元素的宽度和高度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31214564/