Skip to content Skip to sidebar Skip to footer

Flex-box Only Display As Many Items That Fit In A Container

I want to only use CSS to make it so I have a container which is using display: inline-flex. I want this container to only display internal items if they fit within the container a

Solution 1:

Here I added a fixed height to the flex-container and set the flex-wrap to wrap
(and changed the nowrap rule to wrap)

.flex-container {
  overflow: hidden;
  height: 130px;
  max-width: 600px;
  padding: 0;
  margin: 0;
  list-style: none;
  border: 1px solid silver;
  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: inline-flex;
}

.wrap  { 
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
}

.flex-item {
  background: tomato;
  padding: 5px;
  min-width: 100px;
  height: 100px;
  margin: 10px;
  
  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
  flex: 1;
  display: inline-block;
}
<ul class="flex-container wrap">
  <li class="flex-item">1</li>
  <li class="flex-item">2</li>
  <li class="flex-item">3</li>
  <li class="flex-item">4</li>
  <li class="flex-item">5</li>
  <li class="flex-item">6</li>
  <li class="flex-item">7</li>
  <li class="flex-item">8</li>
</ul>

Solution 2:

try this

<ul class="flex-container nowrap">
 <li class="flex-item">1</li>
 <li class="flex-item">2</li>
 <li class="flex-item">3</li>
 <li class="flex-item">4</li>
 <li class="flex-item">5</li>
 <li class="flex-item">6</li>
 <li class="flex-item">7</li>
 <li class="flex-item">8</li>
 <li style="clear:both"></li>
</ul>

css

<style>
 .flex-container {
   max-width: 600px;
  padding: 0;
  margin: 0;
  list-style: none;
  border: 1px solid silver;

}

.flex-item {
  float:left;
  background: tomato;
  padding: 5px;
  min-width: 100px;
  height: 100px;
  margin: 10px;

  line-height: 100px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;

    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    flex: 1 1 auto;
   }
</style>

Solution 3:

Couple of thoughts. First, to detect of a div partially sits outside of it's parent is a javascript trick, not css.

Second, read this awesome guide to flexbox. It will help you clean up your css and make a few things much cleaner for you. It certainly helped me.

Finally, It might be possible with css depending on the fixed sizing your using. Are you going to allow scrolling? why are their hard heights, and min-widths? This may help me guide you to a more tailored solution.


Post a Comment for "Flex-box Only Display As Many Items That Fit In A Container"