如下代码,我通过Flex写了一个类似瀑布流的父元素。
宽度我不希望固定,而是希望根据子元素的数量将父元素撑大。
于是我设置了一个width: max-content。
但子元素明明换行了,父元素却没有撑开。
[XHTML] 纯文本查看 复制代码 <!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> SyntaxHighlighter Copyright 2004-2013 Alex Gorbatchev.
解决办法
方案一:
[CSS] 纯文本查看 复制代码 .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;
} SyntaxHighlighter Copyright 2004-2013 Alex Gorbatchev.
方案二:
[CSS] 纯文本查看 复制代码 .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;
} SyntaxHighlighter Copyright 2004-2013 Alex Gorbatchev. |