Home > Back-end >  how to align flex items to represent a bar chart
how to align flex items to represent a bar chart

Time:01-17

I have been trying to style the react component so that it looks like a horizontal bar chart. However, I am unable to align the centre div to the left as expected.

here is my react component for each row.

import React from 'react'

const level3UnitItem = ({ item, ratio }) => {
    return (
        <div className='country-div' >
            <div className='name-div'> <h1>{item.country}</h1></div>
            <div style={{ width: `${ratio * 400}px`, backgroundColor: 'red' }} className='bar-div'>
            </div>
            <div className='number-div'><h1>{item.population.toLocaleString('en-US')}</h1></div>

        </div>
    )
}

export default level3UnitItem

here is the css

.country-div{
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 1rem;
    margin: .2px;
}
.country-div h1, h2{
    font-size: small;
}

and the current design is

enter image description here

I am expecting it to be

enter image description here

CodePudding user response:

Can you try this? i add div inside the center div. then style it..

import React from 'react'
    
const level3UnitItem = ({ item, ratio }) => {
return (
   <div className='country-div' >
       <div className='name-div'> <h1>{item.country}</h1></div>
           <div >
              <div style={{ width: `${ratio * 400}px`, backgroundColor: 'red' }} className='bar-div'>
           </div>
       </div>
   <div className='number-div'><h1>{item.population.toLocaleString('en-US')}</h1> 
 </div>
</div>
)
}
    
export default level3UnitItem

and as for the css

   .country-div{
      width: 100%;
      display: flex;
      justify-content: space-between;
      padding: 1rem;
      margin: .2px;
   }

  .country-div h1, h2{
     font-size: small;
  }
  
  .__toLeft {
      display: flex;
      justify-content: flex-start;
      align-items: center;
  }

CodePudding user response:

here is the example, you can try this example. Now the result is

CodePudding user response:

You will have to put 'name-div' and 'bar-div' inside another div(a parent div), like this:

import React from 'react'

const level3UnitItem = ({ item, ratio }) => {
return (
    <div className='country-div' >
        <div className="name-bar-container">
         <div className='name-div'> <h1>{item.country}</h1></div>
         <div style={{ width: `${ratio * 400}px`, backgroundColor: 'red' }} className='bar-div'>
        </div>
        </div>
        <div className='number-div'><h1>{item.population.toLocaleString('en-US')}</h1></div>

    </div>
)
}

export default level3UnitItem

CSS for 'name-bar-container' div:

.name-bar-container {
  width: 100%;
  display: flex;
}

you can also add margin-left to 'bar-div' to format it.

  • Related