Home > Blockchain >  TailwindCSS - Set flex child width to fill up whole parent width
TailwindCSS - Set flex child width to fill up whole parent width

Time:11-05

I have this react component:

const Status = () => {
  return (
    <div className='h-screen bg-gray-800 flex justify-center items-center p-16'>
      <div className='bg-gray-700 px-8 py-4 rounded w-full'>
        <h2 className='text-2xl text-gray-100 font-medium'>Plex Server</h2>
        <h3 className='text-base text-gray-400'>Added 22/10/2021</h3>
        <div className='flex flex-row w-full space-x-1 my-4'>
          {[...Array(30)].map((i, idx) => (
            <div key={idx} className='h-8 w-1 bg-green-400 rounded'></div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Status;

I'm using it to render 30 flex children with hard-coded width of 4px (w-1 class). Here is the result:

snippet result

Is there a way to set children width automatically so it would fill up parent space equaly?

For example: parent width is 100px and this time I want to render only 10 elements. With current code it will take only 76px (40px from child width 36px from 4px space between them). Is there a way to set children width automatically to ~6px?

CodePudding user response:

You can do it by using flex-1 instead of w-1 and it will take width automatically such as:

const Status = () => {
  return (
    <div className='h-screen bg-gray-800 flex justify-center items-center p-16'>
      <div className='bg-gray-700 px-8 py-4 rounded w-full'>
        <h2 className='text-2xl text-gray-100 font-medium'>Plex Server</h2>
        <h3 className='text-base text-gray-400'>Added 22/10/2021</h3>
        <div className='flex flex-row w-full space-x-1 my-4'>
          {[...Array(30)].map((i, idx) => (
            <div key={idx} className='h-8 flex-1 bg-green-400 rounded'></div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Status;

Here is a working example of it: enter image description here

  • Related