我正在尝试做一个简单的flex布局:
#header {
background-color: grey;
}
#container {
display:flex;
height: calc(100vh - 50px);
}
#chatAndUserContainer {
display: flex;
width: 100%;
}
#chatContainer {
background-color: red;
width:100%;
}
#usersContainer {
background-color: green;
width:320px;
}
<div id="header">header</div>
<div id="container">
<div id="chatAndUserContainer">
<div id="chatContainer">
chatContainer
</div>
<div id="usersContainer">
usersContainer
</div>
</div>
</div>
问题是:渲染时, #usersContainer的宽度不是320px,而是...274px !
有没有办法纠正这一点?(我需要使用display:flex,而不是绝对的)
发布于 2018-06-20 05:54:10
你正面临着shrink效应。由于总宽度(100% + 320px)大于100%,因此您的两个元素将同样缩小以适合它们的父容器。
要避免这种情况,可以禁用第二个div的收缩:
#header {
background-color: grey;
}
#container {
display:flex;
height: calc(100vh - 50px);
}
#chatAndUserContainer {
display: flex;
width: 100%;
}
#chatContainer {
background-color: red;
width:100%;
}
#usersContainer {
background-color: green;
width:320px;
flex-shrink:0;
}
<div id="header">header</div>
<div id="container">
<div id="chatAndUserContainer">
<div id="chatContainer">
chatContainer
</div>
<div id="usersContainer">
usersContainer
</div>
</div>
</div>
或者不使用div,将其替换为flex:1
,这样第一个div将填充第二个div留下的剩余空间:
#header {
background-color: grey;
}
#container {
display:flex;
height: calc(100vh - 50px);
}
#chatAndUserContainer {
display: flex;
width:100%;
}
#chatContainer {
background-color: red;
flex:1;
}
#usersContainer {
background-color: green;
width:320px;
}
<div id="header">header</div>
<div id="container">
<div id="chatAndUserContainer">
<div id="chatContainer">
chatContainer
</div>
<div id="usersContainer">
usersContainer
</div>
</div>
</div>
发布于 2018-06-20 06:33:15
您可以在#chatContainer
中使用calc()
,或在#usersContainer
中使用min-width
,或者像下面的示例一样使用这两种方法。
#header {
background-color: grey;
}
#container {
display:flex;
height: calc(100vh - 50px);
}
#chatAndUserContainer {
display: flex;
width: 100%;
}
#chatContainer {
background-color: red;
width:calc(100% - 320px);
}
#usersContainer {
background-color: green;
width:320px;
min-width: 320px;
}
<div id="header">header</div>
<div id="container">
<div id="chatAndUserContainer">
<div id="chatContainer">
chatContainer
</div>
<div id="usersContainer">
usersContainer
</div>
</div>
</div>
https://stackoverflow.com/questions/50937398
复制相似问题