CSS,Flex瀑布流父元素宽度的问题
如下代码,我通过Flex写了一个类似瀑布流的父元素。宽度我不希望固定,而是希望根据子元素的数量将父元素撑大。
于是我设置了一个width: max-content。
但子元素明明换行了,父元素却没有撑开。
不知道应该怎么写,请各位大佬指教,感谢。
<!DOCTYPE html>
<html lang="CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
display: flex;
flex-direction: column;
flex-wrap: wrap;
background-color: chartreuse;
width: max-content;
max-height: 30vh;
}
.father>div {
border: 1px solid saddlebrown;
width: 100px;
height: 20px;
display: grid;
place-items: center;
}
</style>
</head>
<body>
<div class="father">
<!-- 模拟瀑布流,子元素数量不定 -->
<div>D1</div>
<div>D2</div>
<div>D3</div>
<div>D4</div>
<div>D5</div>
<div>D6</div>
<div>D7</div>
<div>D8</div>
<div>D9</div>
<div>D10</div>
<div>D11</div>
<div>D12</div>
<div>D13</div>
<div>D14</div>
<div>D15</div>
<div>D16</div>
</div>
</body>
</html> 方案一
.father {
display: flex;
flex-wrap: wrap;
background-color: chartreuse;
max-height: 30vh;
}
.father > div {
border: 1px solid saddlebrown;
flex: 0 1 100px;
height: 20px;
display: inline-grid;
place-items: center;
}
方案二
.father {
display: grid;
grid-template-columns: repeat(auto-fill, 100px);
background-color: chartreuse;
max-height: 30vh;
}
.father > div {
border: 1px solid saddlebrown;
height: 20px;
display: inline-grid;
place-items: center;
}
子元素折行时,父元素的宽度不变是因为父元素的宽度是由子元素的宽度决定的,而子元素折行时,子元素的宽度并没有发生变化,所以父元素的宽度也不会发生变化。 .father {
display: flex;
flex-wrap: wrap;
max-height: 30vh;
background-color: chartreuse;
writing-mode: vertical-lr;
}
.father > div {
border: 1px solid saddlebrown;
width: 100px;
height: 20px;
display: grid;
place-items: center;
writing-mode: horizontal-tb;
} 4楼正解。感谢
页:
[1]