Html 如何根据内容调整 flex div 的宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37300614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to adapt a flex div's width to content
提问by Tomás Francisco
My idea is to give an adaptive div width. When I have just one item, the width should be the same as the item within the container div.
我的想法是给出一个自适应的 div 宽度。当我只有一个项目时,宽度应该与容器 div 中的项目相同。
Any suggestion of how to do this?
关于如何做到这一点的任何建议?
Example: http://codepen.io/tomasfrancisco/pen/PNvLLw
示例:http: //codepen.io/tomasfrancisco/pen/PNvLLw
HTML:
HTML:
<div id="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div id="container">
<div class="item"></div>
</div>
CSS:
CSS:
#container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
max-width: 200px;
padding: 10px;
margin: 20px;
background-color: blue;
}
#container .item {
width: 80px;
height: 50px;
background-color: red;
margin: 10px;
}
回答by Nenad Vracar
You can use display: inline-flex
您可以使用 display: inline-flex
#container {
display: inline-flex;
flex-direction: row;
flex-wrap: wrap;
max-width: 200px;
padding: 10px;
margin: 20px;
background-color: blue;
}
#container .item {
width: 80px;
height: 50px;
background-color: red;
margin: 10px;
}
<div id="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div id="container">
<div class="item"></div>
</div>