问题描述
正如您在下面的代码中看到的,flex 容器内的左侧 div 会拉伸以满足右侧 div 的高度.有没有我可以设置的属性,使其高度成为保存其内容所需的最小值(就像通常的 height: auto
div 在 flex 容器外)?
#a {显示:弹性;}#a >div {背景颜色:红色;填充:5px;边距:2px;}#b {高度:自动;}
<div id="b">左</div><div>right<br>right<br>right<br>right<br>right<br></div>
align-items
或 align-content
属性分别控制此行为.
align-items
定义项目的位置垂直到flex-direction
.
默认的flex-direction
是row
,因此垂直放置可以通过align-items
来控制.
还有 align-self
属性来控制每个项目的对齐方式.
#a {显示:弹性;对齐项目:flex-start;对齐内容:弹性开始;}#a >div {背景颜色:红色;填充:5px;边距:2px;}#a >#C {对齐自我:伸展;}
<div id="b">左</div><div id="c">中间</div><div>right<br>right<br>right<br>right<br>right<br></div>
css-tricks 有一篇很棒的文章话题.我建议多读几遍.
As you can see in the code below, the left div inside the flex container stretches to meet the height of the right div. Is there an attribute I can set to make its height the minimum required for holding its content (like usual height: auto
divs outside flex containers)?
#a {
display: flex;
}
#a > div {
background-color: red;
padding: 5px;
margin: 2px;
}
#b {
height: auto;
}
<div id="a">
<div id="b">left</div>
<div>right<br>right<br>right<br>right<br>right<br></div>
</div>
The align-items
, or respectively align-content
attribute controls this behaviour.
align-items
defines the items' positioning perpendicularly to flex-direction
.
The default flex-direction
is row
, therfore vertical placement can be controlled with align-items
.
There is also the align-self
attribute to control the alignment on a per item basis.
#a {
display:flex;
align-items:flex-start;
align-content:flex-start;
}
#a > div {
background-color:red;
padding:5px;
margin:2px;
}
#a > #c {
align-self:stretch;
}
<div id="a">
<div id="b">left</div>
<div id="c">middle</div>
<div>right<br>right<br>right<br>right<br>right<br></div>
</div>
css-tricks has an excellent article on the topic. I recommend reading it a couple of times.
这篇关于如何使弹性项目不填充弹性容器的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!