Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to adapt a flex div's width to content

Tags:

html

css

flexbox

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.

Any suggestion on how to do this?

#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; }
<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>
like image 811
Tomás Francisco Avatar asked May 18 '16 13:05

Tomás Francisco


People also ask

How do you adjust flex width?

You have to add a wrapper around the right column, and then only specify flex-basis on the . menu element. Now when the menu is hidden, the right column expands the full amount. Great, that works as expected!

How do you make a flex item full width?

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100% , and enable wrap on the container. The item now consumes all available space.

How do you adjust the flex-wrap in CSS?

The CSS flex-wrap property is used to specify whether flex items are forced into a single line or wrapped onto multiple lines. The flex-wrap property allows enabling the control direction in which lines are stacked. It is used to designate a single line or multi-line format to flex items inside the flex container.


1 Answers

You can use 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>
like image 192
Nenad Vracar Avatar answered Oct 08 '22 18:10

Nenad Vracar