What is the best way to vertically align items within a <div> using CSS in a React application?

The layout of the page looks like this:

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

I am trying to center the Redbox (containing '1') within the "PlayerOneDiv".

Similarly, I want to center the yellow box within "PlayerTwoDiv".

return (<div className="App">
        <div className="sampleDiv" onClick={getData}>
            <div className="playerOneScoreDiv">1</div>
            <div className="midDiv">
                <Box param={pitValue1} funcParam={getData}> b</Box>
            </div>
            <div className="playerTwoScoreDiv">3</div>
        </div>

The styling for PlayerOneDiv and the outer div is as follows:

  .sampleDiv {
    background-color: green;
    margin: auto;
    width: 60%;
    padding: 100px;
    border-radius: 14px;
    display: flex;
    flex-direction: row;
}

.playerOneScoreDiv {
    width: 15%;
    height: 96px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 3rem;
    font-weight: bold;
    border-radius: 14px;
    color: #fff;
    margin-right: 4px;
    margin-bottom: 4px;
    cursor: default;
    background-color: red;
}

Even though the number "1" in PlayerOneDiv shifts properly, the entire box does not center within the div.

Which CSS property should I adjust or should I introduce an additional wrapper div?

Answer №1

Here is a code snippet that can provide insight into your situation.

.sampleDiv{
  display: flex;
  gap:10px;
  justify-content: space-around;
}
.playerOneScoreDiv,
.playerTwoScoreDiv{
  background: red;
  flex-basis: 25%;
  display: flex;
  align-self: center;
  justify-content: center;
}
.midDiv{
  background: green;
  flex-basis: 50%;
}
<div class="sampleDiv">
    <div class="playerOneScoreDiv">1</div>
    <div class="midDiv">
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
    </div>
    <div class="playerTwoScoreDiv">3</div>
</div>

Let me walk you through this code:

  • The parent div sampleDiv uses flex, with justify-content: space-around as one key aspect. For further details on justify-content, refer to justify-content
  • If the default setup doesn't meet your requirements, consider making each child div a new flex element and using align-self:center for alignment control across the cross axis. More options for align-self can be found at align-self
  • gap introduces spacing between individual flex items
  • flex-basis determines the size of each flex item

Answer №2

HTML and CSS:

<div id="container">
  <div id="left">
    
  </div>
  <div id="middle">
    
  </div>
  <div id="right">
    
  </div>
</div>

#container {
  width: 220px;
  height: 32px;
  background-color: khaki;
  overflow-x: clip;
  display: flex;
}

#left {
  justify-content: left;
  width: 32px;
  float: left;
  height: 32px;
  line-height: 32px;
  background-color: darkkhaki;
}

#middle {
  width: 32px;
  height: 32px;
  margin: 0 auto;
  background-color: darkkhaki;
}

#right {
  width: 32px;
  height: 32px;
  float: right;
  background-color: darkkhaki;
}

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

What could be the reason for <input type="email"> flagging legitimate email addresses as invalid?

According to information from Wikipedia, the following email addresses are considered valid. " "@example.org "john..doe"@example.org "very.(),:;<>[]\".VERY.\"very@\\ \"very\". ...

Creating a database using Angular2+ in CouchDB can be achieved by following these steps

I have been attempting to set up a database in couchdb using angular2+. My goal is to create a button that, when clicked, will initiate the creation of the database. However, I keep encountering an error message. "ERROR Error: Uncaught (in promise): H ...

The children elements in the Flexbox div are not lined up inline with the text

Review the snippet below: div { display: flex; flex: 0 0 45%; max-width: 45%; } <div>Lorem ipsum dolor sit amet, <strong>dolor sit</strong>tempor incididunt ut la.tempor incididunt ut la.tempor incididunt ut la.tempor incididunt ut ...

Displaying Unicode CSS Font Awesome Icons as Boxes in a React Project

I have incorporated the jPlayer example into a create-react-app. Encountering an issue where font-awesome icons are displaying as boxes in this CodeSandbox illustration. https://codesandbox.io/s/peaceful-heisenberg-d59nz?fontsize=14&hidenavigation=1&a ...

When employing useNavigation, the URL is updated but the component does not render or appear on the

Check out this code snippet: https://codesandbox.io/p/sandbox/hardcore-lake-mptzw3 App.jsx: import ContextProvider from "./provider/contextProvider"; import Routes from "./routes"; function App() { console.log("Inside App" ...

leveraging a value in react elements

Embarking on my React journey, I have encountered new challenges. Seeking your insights to help me overcome this hurdle. My goal is to capture input values and add them to a list area. Essentially, I want to fetch state.inputValue and append it in the ul s ...

How to efficiently retrieve parent content from a child component

parent.html <ion-content class="project"> <ion-grid> <ion-row class="details"> <project [data]="data"></project>// this child component </ion-row> </ion-grid> </ion-content> project.ht ...

Sending a prop to a handler causes issues with navigation paths

I'm facing an issue with my handler and button component setup. Here's my handler: const addToCartHandler = (id) => { navigate(`/cart/${brand}/${id}?qty=${qty}`)}; And here's the button component using the handler: <Button onClick={a ...

Utilizing Fancybox with a polymer paper-card: A step-by-step guide

I have a collection of paper-cards and I am looking for guidance on integrating the fancybox library to display the content of each paper-card. Here is a sample of a paper-card: <paper-card heading="Emmental" image="http://placehold.it/350x150/FF ...

Can a custom subscribe() method be implemented for Angular 2's http service?

Trying my hand at angular2, I discovered the necessity of using the subscribe() method to fetch the results from a get or post method: this.http.post(path, item).subscribe( (response: Response)=> {console.log(response)}, (error: any)=>{console.l ...

Does React.lazy callback have a guarantee of being executed just once?

Does the callback for React.lazy run exactly once? An example use-case is injecting RTK & RTKQ endpoints as shown below: const Component = React.lazy(() => { injectApi(componentApi) injectStore(componentStore) return import('compon ...

Trigger a component update by clicking on it

I am currently working on a feature that involves displaying a new string on the page whenever a button is clicked. I have set up a service that returns the desired string when the button is tapped, and this part is functioning correctly as I can log and a ...

CSS Tutorial: Creating a Dynamic Gradient Bar

I am looking to create a dynamic colored bar with a moving color gradient effect. Without using JavaScript, I want to achieve this effect using CSS 3 properties such as gradients and animations. This is a snippet of what I have tried so far: HTML: <b ...

What could be the reason behind getting a useLayoutEffect error when using renderToString to render a Material-UI component?

Currently, I am utilizing React version 16.12.0 along with @MaterialUI/core version 4.8.1. The challenge I am facing involves creating a custom icon for a React Leaflet Marker. The icon in question is a Fab component sourced from Material-UI. In order to ...

In order to effectively manage the outcome of these loaders, it might be necessary to incorporate an extra loader into the equation. Node.js version

./node_modules/html-to-react/node_modules/htmlparser2/lib/esm/index.js 67:9 Module parse failed: Unexpected token (67:9) File was processed with these loaders: * ./node_modules/babel-loader/lib/index.js You may need an additional loader to handle the resu ...

Creating a dynamic selection in Angular without duplicate values

How can I prevent repetition of values when creating a dynamic select based on an object fetched from a database? Below is the HTML code: <router-outlet></router-outlet> <hr> <div class="row"> <div class="col-xs-12"> & ...

Insert a new, unique div onto an HTML webpage using JavaScript, ensuring no duplicates are created

Having an issue with this code snippet where nothing is being added. It seems like the variable result may not be taking a number or something else, but I'm not entirely sure why. $(document).ready(function () //document.getElementById(1).style. ...

What is the process for reinserting a list item into the nested elements?

Looking for help with manipulating a menu in HTML? I have a menu that I want to modify by removing and adding list items. While I've had success removing items, I'm struggling to properly use the add method. Here's an example of what my menu ...

Troubleshooting issues with rowspan in a Datatable

I am currently utilizing jQuery DataTables to display my grid data and implementing the rowspan concept with the rowsGroup option. Initially, it works well by spanning some rows and looking visually pleasing, but eventually, it starts failing. Here are so ...

Is there any code for displaying the action form?

I'm brand new to PHP and just tried a simple form processing program I found in a book: <!doctype html> <head> <meta charset="utf-8"> <title>Bob's Parts Store</title> </head> <body> <form action = ...