【发布时间】:2017-09-08 01:31:45
【问题描述】:
在这支笔/小提琴中,我创建了一个非常非常简单的页面布局用于演示目的:See Pen/Fiddle here!
在浅蓝色的“内容”区域中,我有一个类为 flex-container 的 div,其中包含一个标题和一个 div 嵌套的图像。
<div class="content">
<div class="flex-container">
<h1>Nice Image</h1>
<div>
<img src="http://loremflickr.com/800/800" />
</div>
</div>
</div>
我遇到的问题是,每当我将第 53 行中的图像 parent-div 高度设置为 100% 时,图像就会溢出。我开始玩弄它,一旦我将高度设置为小于 100%,图像就会很好地缩放以适应 div 的剩余高度,即 flex-growth 父 div 占据的区域。
.content {
background-color: rgba(0, 0, 255, 0.3);
overflow: hidden;
position: relative;
height: 100%;
box-sizing: border-box;
.flex-container {
height: 100%;
display: flex;
flex-direction: column;
background-color: rgba(255, 255, 255, 0.5);
>div {
flex-grow: 1;
height: 1%;
}
img {
height: 100%;
}
}
}
我想知道这是为什么?这种方法感觉不是很干净,我想知道如何改进该布局以使其感觉不那么“hacky”。
完整的 HTML:
<div class="container">
<div class="header">Nav</div>
<div class="nav">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
<div class="content">
<div class="flex-container">
<h1>Nice Image</h1>
<div>
<img src="http://loremflickr.com/800/800" />
</div>
</div>
</div>
<div class="status">
<p>Status: Lorem ipsum dolor sit amet</p>
</div>
</div>
完整的 SCSS:
html, body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
ul, h1, p, img {
margin: 0;
padding: 0;
}
.container {
background-color: rgba(0, 0, 0, 0.2);
height: 100%;
width: 100%;
overflow: hidden;
padding: 38px 0px 30px 161px;
box-sizing: border-box;
.header {
background-color: rgba(255, 0, 0, 0.3);
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 38px;
}
.nav {
background-color: rgba(0, 255, 0, 0.3);
position: fixed;
left: 0;
width: 161px;
height: 100%;
}
.content {
background-color: rgba(0, 0, 255, 0.3);
overflow: hidden;
position: relative;
height: 100%;
box-sizing: border-box;
.flex-container {
height: 100%;
display: flex;
flex-direction: column;
background-color: rgba(255, 255, 255, 0.5);
>div {
flex-grow: 1;
height: 1%;
}
img {
height: 100%;
}
}
}
.status {
background-color: rgba(255, 255, 0, 0.3);
position: fixed;
left: 161px;
bottom: 0;
width: 100%;
height: 30px;
}
}
【问题讨论】:
-
当您为 div 设置高度值并将其重置为 1 时,高度会更新以填充剩余空间。它允许孩子更新高度的父值。删除 flex 或 height ,它会再次中断。两条规则都需要;)