Tips on positioning flex items to create a visually appealing bar chart design

I've been working on customizing the appearance of a React component to resemble a horizontal bar chart. However, I'm facing difficulties aligning the center div to the left as intended.

Below is the code for 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 corresponding CSS:

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

The current design appears as follows:

https://i.sstatic.net/9gDyl.png

My desired output should look like this:

https://i.sstatic.net/gKenH.png

Answer №1

To properly structure your code, ensure that 'name-div' and 'bar-div' are enclosed within a parent div as shown below:

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

Make sure to include the following CSS for the 'name-bar-container' div:

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

If needed, you can also adjust the formatting by adding margin-left to the 'bar-div'.

Answer №2

Could you test this out? Attempting to insert a div inside the central div and then customize its style.

import React from 'react'
    
const level3UnitItem = ({ item, ratio }) => {
return (
   <div className='country-div' >
       <div className='name-div'> <h1>{item.country}</h1></div>
           <div class="__toLeft">
              <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

Regarding the css styling:

   .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;
  }

Answer №3

I found a way to align the elements by grouping the last two divs (inside the parent div) into a new div, and that resolved my issue.

import React from 'react'

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

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

.country-div h1, h2{
   font-size: small;
}
.name-div{
    width: 300px;
}
.barbar-div{
    width: 100%;
    display: flex;
    justify-content: space-between;
}

https://i.sstatic.net/akehR.png

Answer №4

1. Begin by creating a container element and setting its display property to "flex" in order to transform it into a flex container.

2. Next, generate the individual flex items that will serve as the bars of the chart. These can either be div elements or any other HTML elements of your choice.

3. Adjust the width of each flex item to the appropriate percentage according to the data you wish to visualize in the chart. For example, if you aim to represent a 50% value, set the width of the flex item to 50%.

4. Assign a fixed height to each flex item, such as 20px, to ensure consistent bar heights throughout the chart.

5. Utilize the align-items property on the flex container to vertically align the bars. To center the bars vertically within the container, you may use "align-items: center".

6. Employ the justify-content property on the flex container to horizontally align the bars. For instance, utilize "justify-content: space-between" to evenly distribute the bars across the container.

7. Enhance the appearance of the flex items by adding colors and additional styling to make them visually resemble bars in a traditional chart.

8. Lastly, incorporate labels and text elements into the chart to offer context and details regarding the displayed data.

Note: To ensure responsiveness, employ media queries to adjust the width and height of the flex items and container based on the screen size.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Organizing table data by columns in a continuous loop

I'm currently working on extracting data from a database, organizing it into tables (potentially multiple tables), and presenting them in columns of 4 across several pages. My main concern is figuring out how to display the tables horizontally like t ...

The module "@uploadthing/react" does not contain the exported member "FileWithPath"

'use client' import type { FileWithPath } from '@uploadthing/react' import { useCallback, Dispatch, SetStateAction } from 'react' import { useDropzone } from '@uploadthing/react/hooks' import { generateClientDropzon ...

Adjust the height of an element when the maximum height is set to none

I am trying to add animation to the opening of a menu on my website. This is achieved by adjusting the max-height property of the <div> element that represents the menu, as well as changing the display property. The max-height value is being changed ...

Arrange elements within a navigation bar

As a beginner in coding, I am taking on the challenge of creating a webpage for a student project using React. I've hit a hurdle while working on the navbar for the page. How can I align the items (Home, Project, Team, Contact) to the right side of t ...

Using the spread operator in the console.log function is successful, but encountering issues when attempting to assign or return it in a

Currently facing an issue with a spread operator that's really getting on my nerves. Despite searching extensively, I haven't found a solution yet. Whenever I utilize console.log(...val), it displays the data flawlessly without any errors. Howev ...

Ensure that the text stays aligned at the center within an `<li>` tag, especially when there is an image along with the text within the element

I have a basic list structured like this: <ul> <li>ONE</li> <li>TWO</li> <li>THREE</li> <li>FOUR</li> <li>FIVE</li> <li>SIX</li> <li><hr&g ...

What is the best way to utilize data obtained from a POST request in order to carry out a subsequent

I'm currently working on a project that involves integrating the Spotify API into a web application. The goal is to take a user-submitted search keyword, send it to the server for processing, and then receive and display the search results on the fron ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Is it possible to restrict the draggable area?

Looking at this JSFiddle example, there is a box that can be dragged around the body. But, is it feasible to restrict dragging only when the user clicks on the purple section identified by the id "head"? $(document).ready(function(){ $( "#box" ).dra ...

Steps for creating a Spotify playlist with React

Can someone help me with an issue I'm having while trying to create a playlist on localhost and save it to Spotify? The Save to Spotify button doesn't seem to be working properly. I suspect there might be an issue with the fetching part of the co ...

Can we bring flexbox inserts, removes, and item positioning to life through animation?

This question was first raised in 2012, but the responses provided didn't address my specific situation (smooth transition for rearranging wrapped content). "After removing an item from a flexbox, the remaining items snap into their new positions imm ...

What is the best way to begin the main page content below the stationary header in order to prevent any overlap with the hyperlink section?

I have created this HTML page, but I am facing an issue where the hyperlinked sections overlap with the static header when clicked on. I want all linked sections to appear below the header and each section to have different dimensions within the iframe. I ...

What are the steps to seamlessly embed Rocket.chat Omnichannel livechat into an iframe without the open/close button?

I am looking to add a live chat feature in an iframe on my website without the open/close button, only utilizing the onichannel chat layout. I attempted something like the following: 'use client'; import React from 'react'; export con ...

Utilize flexbox to align two buttons side by side and manage their positioning

I have a collection of buttons that I want to display in rows of two. I am looking for a way to set the specific width of each button and decide whether they should be aligned left, center, or right. Ideally, the outcome would resemble the following: http ...

The React State variable has been declared, but it is being mistakenly interpreted as undefined, resulting in an error being displayed in

When I set the value of inStock : false at this.state inside constructor, and then use it in the groupByCategory() function with an if( this.state.inStock ), it returns undefined. However, if I change it to 'this.state?.inStock', it works fine. I ...

Minimize unnecessary model replication across the database, server-side, and client-side components

Currently, I am developing a web application using Flask with no ORM, MySQL as the database backend, and React for the frontend. My main concern is that my model appears to be duplicated across MySQL, Flask, and React. For instance, if we consider the foll ...

Enhancing Twitter Bootstrap with custom media queries for an extra-small breakpoint

It came as a surprise to me that Twitter Bootstrap does not include media queries specifically for creating a well-suited version of a website for mobile portrait screens. Defining the width for "mobile portrait" is a bit complicated. In the past, most ph ...

Guide to dividing the screen into three horizontal sections

I am currently working on a website and trying to divide a page into three different sections: one for the title and a button, one for the content, one for the text input. . The issue I'm facing is that the divs are not filling the height and ...

Utilizing ReactJS for Web Development with Enhanced Data Insights from Google

Utilizing Google Analytics and various tools, I've encountered an issue with the development of ReactJS. My goal was to collect analytics data from my website by using react-helmet to dynamically change the title and the HTML lang parameter based on t ...

Is there a way to search for text and highlight it within an HTML string using Ionic

Welcome everyone! I am currently utilizing Ionic to load an article from a local HTML string. <ion-content padding> <p [innerHTML]="url"></p> </ion-content> The 'url' variable contains the local HTML string. My goal ...