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:

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

Update the color of the label on the ng2-charts/charts.js pie chart

I am currently using ng2-charts and have successfully created a beautiful pie-chart with labels and data. However, I am unable to change the default grey color of the labels. Is this normal? How can I override the default label color? It appears that the ...

A unique string containing the object element "this.variable" found in a separate file

Snippet of HTML code: <input class="jscolor" id="color-picker"> <div id="rect" class="rect"></div> <script src="jscolor.js"></script> <script src="skrypt.js"></script> Javascript snippet: function up ...

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...

Tips for managing the outcome of an HTTP Post request

I am currently working with Angular 2 and Node.js, attempting to incorporate braintree into my project, which has proven to be quite challenging. My current approach involves utilizing an HTTP Post request to send back the result object from the transacti ...

Issue with Typescript Application not navigating into the node_modules directory

After attempting to load the app from the root directory of our server, it became clear that this was not a practical solution due to the way our application uses pretty URLs. For instance, trying to access a page with a URL like http://www.website.com/mod ...

increase the selected date in an Angular datepicker by 10 days

I have a datepicker value in the following format: `Fri Mar 01 2021 00:00:00 GMT+0530 (India Standard Time)` My goal is to add 60 days to this date. After performing the addition, the updated value appears as: `Fri Apr 29 2021 00:00:00 GMT+0530 (India St ...

Encountering an issue with Angular 5.2 application build on VSTS build server: Running into "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" error

Out of nowhere, the builds began failing with the following error : 2019-01-03T12:57:22.2223175Z EXEC : FATAL error : CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error MSB3073: The command "node node_modules/webpack/bin/w ...

script to pause video using jQuery

I have a script that works perfectly, but currently it only stops an instance of a playing video if a new video is started. I want to modify the script so that ALL instances of playing videos are stopped when the function stopAllButMe(); is called. Can s ...

"Enhancing the spacing between background images through CSS: A guide to using the repeat property

Looking to design a background with a repeating image using CSS. background: url(../images/bg.PNG) repeat; However, facing an issue where the images are too close together. Any suggestions on how to add padding around each image? ...

Having trouble viewing the images that were uploaded with Multer using React, Node.js, Sequelize, and PostgreSQL

Is there a way to enable users to click on the default avatar and upload their own image? Although I can successfully upload files to the database, I'm facing issues in accessing them from the client side. It seems like I might not be storing them cor ...

Creating the perfect redux store: Best practices for designing a seamless structure

Having recently delved into the world of redux, I find myself questioning my current architecture. I am eager to learn a better approach to structuring my application from those with more experience in the field. My main concern is that while aiming to ke ...

Background image in Bootstrap not covering entire web page

I am facing an issue where the background image is confined within the constraints of the login panel, and I'm unsure why. My goal is for the image to span the full width and height of the browser window. Any assistance on this matter would be greatly ...

Is there a way to modify the color of the burger icon by utilizing iconStyleLeft or a different technique?

Attempting to modify the color of the default burger icon on the left using iconStyleLeft, but unfortunately the color remains unchanged. import React from 'react'; import AppBar from 'material-ui/AppBar'; import {grey50, grey900 } fr ...

Adapting the colors of various elements throughout the entire webpage

My goal is to incorporate color-switch buttons on my webpage. When these buttons are clicked, I want the existing colors to change to different shades. However, my challenge lies in the fact that these colors are used for various elements such as backgro ...

"What is the best approach to adjusting the width of one div based on the width of another div using CSS Grid

As a beginner in programming, I'm trying to work with CSS Grid but facing some challenges. My goal is to create a component with two columns: the left column should have a width of minmax(570px, 720px), and the right column should be minmax(380px, 10 ...

Utilizing Google Closure Library with Angular 6

I am looking to integrate the google closure library into my angular 6 application. To achieve this, I have utilized the following commands: npm install google-closure-compiler and npm install google-closure-library. My application can be successfully co ...

There seems to be a white space problem located beneath the header photo and the initial

I'm a beginner at coding and working on this project for fun. I'm almost done, but I can't get rid of a white space that's dividing my header from the first section. See the screenshot below: https://i.stack.imgur.com/a1flt.png Even af ...

Transfer a downloaded file from a secured pathway to the web browser

I have a setup with a react frontend and a nodejs/express backend. The backend has a protected route for serving files (downloads) like so: GET /api/file/:id When the frontend initiates a file download, it makes a request to this endpoint using the follo ...

You cannot nest a map function within another map function in React

Having some trouble applying the map function in HTML using React. Below is the code snippet: response = [ data : { name: 'john', title: 'john doe', images: { slider: { desktop: 'link1', mo ...

Forwarding routes with Angular Router

My server has specific mappings for different URLs: / serves an Angular application with routing capabilities /admin serves a Django control panel for staff database updates /api and /api/... serve REST endpoints to handle queries and return JSON data I ...