html - How to adapt div's width to content with flexbox -


i want adapt .flexrow div's width content can't set flex.

html

<div class="fullwidth">   <div class="sidebar">     <p>sidebar</p>     <p>sidebar</p>     <p>sidebar</p>     <p>sidebar</p>     <p>sidebar</p>     <p>sidebar</p>   </div>   <div class="center">     <div class="flexrow">       <div class="card">         <p>card</p>       </div>     </div>   </div> </div> 

css

.center {   display: flex;   justify-content: center; }  .flexrow {   display: inline-flex;   flex-direction: row;   flex-wrap: wrap; }  .flexrow .card {   width: 300px;   height: 60px;   background-color: red;   margin: 10px;   padding: 10px;   text-align: center; } 

i have created snippet here

this example of want: example

any suggestion?

the main problem here when item wrap, whether 1 use flexbox or not, container won't adjust width new content width.

with existing markup, here simple fix in 2 steps achieve that:

  1. add justify-content: center; .flexrow rule

  2. for every possible column need 1 less ghost element push elements on last row way left. added elements new .flexrow .card:empty rule magic.

    .flexrow .card:empty {   height: 0;   margin: 0 10px;   padding: 0 10px; } 

updated codepen

stack snippet

.fullwidth {    background-color: grey;    display: flex;  }    .sidebar {    flex: 0 0 280px;    margin: 10px;    padding: 10px;    background-color: black;    color: white;  }    .flexrow {    display: flex;    flex-wrap: wrap;    align-content: center;    justify-content: center;  }    .flexrow .card {    width: 300px;    height: 60px;    background-color: red;    margin: 10px;    padding: 10px;    text-align: center;  }    .flexrow .card:empty {    height: 0;    margin: 0 10px;    padding: 0 10px;  }
<div class="fullwidth">    <div class="sidebar">      <p>sidebar</p>      <p>sidebar</p>      <p>sidebar</p>      <p>sidebar</p>      <p>sidebar</p>      <p>sidebar</p>    </div>    <div class="center">      <div class="flexrow">        <div class="card">          <p>card</p>        </div>        <div class="card">          <p>card</p>        </div>        <div class="card">          <p>card</p>        </div>        <div class="card">          <p>card</p>        </div>        <div class="card">          <p>card</p>        </div>        <div class="card">          <p>card</p>        </div>        <div class="card">          <p>card</p>        </div>          <!-- ghost elements, if max columns 4 1 need 3 -->        <div class="card"></div>        <div class="card"></div>        <div class="card"></div>        </div>    </div>  </div>


Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -