What is the best way to generate two <div> elements, with one of them being centrally fixed?

When it comes to CSS, I must admit that it's not my strong suit. My current challenge is to create two boxes or divs where one remains fixed in the center of the page, while the other adapts and positions itself right next to the first one. Essentially, I want to construct a textField at the center of the page (the first div) and position a loading spinner (as the second div) next to the textField.

I've been experimenting with achieving this using styled-components:

<StyledBox>
   <StyledTextFieldContainer>
     <TextField/>
   </StyledTextFieldContainer>
   <StyledLoaderContainer>
     Loading...
   </StyledLoaderContainer>
</StyledBox>

const StyledBox = styled(Box)`
  width: 90%;
  justify-content: center;
  align-items: center;
  display: flex;
`;

const StyledTextFieldContainer = styled(Box)`
  width: 70%
  display: flex;
  align-items: flex-end;
`;

const StyledLoaderContainer = styled(Box)`
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
`;

The issue I'm facing is that my textField isn't perfectly centered because the Loader seems to be pushing it slightly to the left (I suspect this happens because both elements are centered).

Here's a CodeSandBox link for reference: https://codesandbox.io/s/weathered-tree-r4tdm?file=/src/App.js

Any suggestions on how I can keep the textField fixed in the center of the page with the Loader positioned right next to it?

Answer №1

After running some tests in the sandbox environment, it appears that this code will serve your needs if you specifically require the div(s) to be centered on the page.

import { Box, TextField } from "@material-ui/core";
import styled from "styled-components";
import "./styles.css";

export default function App() {
  return (
    <StyledBox>
      <div width="70%">
        <TextField label="Fixed in the center" />
      </div>
      <div>
        Loading...
      </div>
    </StyledBox>
  );
}

const StyledBox = styled(Box)`
  position: absolute;
  top: 50%;
  left: 50%;
  background:red;
  transform: translate(-50%,-50%);
  width: 90%;
  justify-content: center;
  align-items: center;
  display: flex;
`;

Answer №2

https://i.sstatic.net/0pX8m.png

Do you want it to look like this? Then simply add a single line in the code for margin-top or padding-top based on your specific requirements.

const StyledBox = styled(Box)`
  position: absolute;
  width: 90%;
  justify-content: center;
  //align-items: center;
  display: flex;
  margin-top: 40vh;
`;

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

creating a mixin for a box-shadow value of none in LESS CSS

I'm encountering a challenge with implementing the box-shadow mixin in LESS css. Here's the mixin for box-shadow: .boxShadow (@x, @y, @blur, @spread: 0, @alpha) { -webkit-box-shadow: @x @y @blur @spread rgba(0, 0, 0, @alpha); -moz-box-s ...

Can React be integrated with GitHub Pages despite its static website nature?

Is it possible to use Node for server-side functionality on a github.io site, even though github.io is typically used for static websites? I've seen tutorials on incorporating React, but unsure about integrating server-side programming. Thank you in a ...

A helpful guide on displaying validation errors in a form using React JS

After creating a form and connecting it to the server, I encountered an issue with displaying validation errors below respective input fields. The error message response in case of validation error is as follows: "message": "ValidationError: confirmPasswor ...

Create a layout using jquery-tokeninput

Currently, my project incorporates jQuery-tokenInput and everything is functioning properly. However, I now have the desire to customize the design of the results that are displayed. For example, I want to adjust the width or make any other design changes. ...

React: Error encountered - React-Redux problem detected

My reactjs web app has been running smoothly until this morning when I encountered the following error: Uncaught Error: You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it do ...

Tips for displaying real-time Firebase database data in a React JS component

https://i.sstatic.net/JpBSc.png https://i.sstatic.net/glyJe.png https://i.sstatic.net/ncR4j.png import React, { useState ,useEffect} from 'react'; import { Link ,useHistory,useParams} from 'react-router-dom'; import { getDatabase,ref, ...

Adjusting HTML/CSS for various screen sizes and devices

I have designed a website, but when it is viewed on devices like iPad or iPhone, the layout does not adjust to fit the screen properly. The text box containing my name and social media buttons appears on the left side, while the background image is positio ...

The HTML element <p> is not spilling over onto a new line

Having trouble with text overflow in a kanban board? I've tried various CSS styling options like overflow-wrap: break-word;, word-wrap: break-word;, and hyphens: auto;, but nothing seems to work. Here's a preview. I'm using Vue.js, but I do ...

CSS outline not displaying correctly in latest version of Internet Explorer

Currently delving into the UI of my web design project. I have come across an issue where the outlined feature in a specific div is not displaying properly in IEv11. Below is a snippet of the CSS code causing the problem... .samp-banner:focus, #samp- ...

What is the best way to loop through an array and display a datalist in JSX?

In my React project, I am attempting to create a datalist using an array. Interestingly, when I pass the array and iterate through it, I can easily log the value of 'city' to the console. However, when I try to do the same iteration without JSX, ...

Creating dynamic grids in React.js by utilizing HTML

Currently, I am tackling one of the projects on FCC which is the Game of Life. Prior to diving in, my focus is on figuring out how to render a grid on the page. I aim to modify the table dimensions while ensuring it fits neatly within its container. The ...

Fluid and static containers in Bootstrap offer flexible and fixed-width layout

I am experimenting with combining fluid containers and fixed containers within a single page layout using Bootstrap. For example, I want to have a large image as a hero unit that spans 100% of the width and height of the viewport, or three column images e ...

What is the best way to append a single class while also ensuring any previously added classes are removed?

How can I apply the selected class and remove any previously selected classes? <html> <select name="Button-Style" id="Button-Style" style="width:100%;"> <option value="Sun-Flower">Sun Flower</option> <option value ...

useEffect invoked repeatedly

I've come across this reactjs code: import React, { useState, useEffect } from 'react' const Test = () => { const [counter, setCounter] = useState(0) useEffect(() => { const data = localStorage.getItem('counter&a ...

Allow action creators the option to refrain from dispatching an action

One of the action creators in my codebase is as follows: export const toggleLoginModal = () => { return { type: "TOGGLE_LOGIN_MODAL", }; }; In my container component, I'm utilizing this action creator with connect(): export default conne ...

use jquery to highlight a table row based on the current hour

Within my HTML structure, there is a table element with the class <table class="model">, and it contains several table data cells with the class class="model-date". The date format within these cells is as follows: DD-MM HH:MM For example, <td ...

The value entered for creating a payment method is invalid: the card must be in the form of an object

I am in the process of setting up a payment method using the Next.js library from Stripe. Here is the code snippet: import React, { FunctionComponent } from 'react'; import type { DisplaySettingsProps } from '@company/frontoffice/types' ...

Ways to place a background image without using the background-position attribute

On the menu of this page (blog.prco.com), I have added a background image for the hover effect on the elements. However, when hovering, the dot seems to move towards the final position from its origin point. My question is, how can I center the image belo ...

Error encountered during react parsing: An unexpected '#' error was encountered when using the react-router-sitemap npm package

I'm currently working on building a sitemap using the react-router-sitemap npm package. After installing all the necessary dependencies related to react-router-sitemap, I created a file called sitemap-generator.js and added the following code. router ...

Creating eight equal sections within HTML <div> elements using Bootstrap

I am brand new to Angular. I need to design something like this: https://i.sstatic.net/Zcb9i.png However, I'm struggling to find the right solution. Here is what I have so far: https://i.sstatic.net/7hsrk.png. Having been a backend developer, I&ap ...