-1

I'm trying to center a div but it seems the perent div is wider than it should be. I could center it with using margin:100px auto. But why i can't do it with top and left?

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './components/App.js';
import './style/index.css'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <BrowserRouter>
        <React.StrictMode>
            <App />
        </React.StrictMode>
    </BrowserRouter>
);

App.js


import {Route, Routes} from 'react-router-dom'
import '../style/App.css'

import LoginForm from "./LoginForm"
function App() {
  return (
    <div className="App">
        <Routes>
            <Route path = '/login' element = {<LoginForm/>} />
        </Routes>
    </div>
  );
}
export default App

LoginForm.css

.card{
    position: absolute;
    top:50%;
    left:50%;
    width: auto;
    background:white;
    border-radius: 50px;
}

1 Answers1

0

Since you used position: absolute you can add transform: translate(-50%, 0);

And you can also use something like grids or flexboxes.

  • That worked, but you have any idea why is not working only with top,left 50%? It's like the size of the perent div is wrong but idk. I'm checking using right:0% and it goes off screen – Ariel Alvaro Oct 21 '22 at 19:09
  • Great, if you can select as a working answer, it was the old way of centering a div, but I assume you will find the answer here https://stackoverflow.com/questions/42121150/css-centering-with-transform – Mohamed Ashraf Oct 21 '22 at 19:21
  • 1
    @ArielAlvaro I answered your other question regarding this here: https://stackoverflow.com/a/74168269/1944. The reason why absolute top, left, 50% doesn't work is because it places the top and left edge of the box at 50%. What you want is to place the *centre* of the box at 50%. So Mohamed's `transform: translate(-50%, 0);` pulls your box back by half its size so the centre sits at 50%. But, unless you _need_ to use `absolute` positioning, it's better to use other methods. Here's an article to read: https://www.freecodecamp.org/news/how-to-center-anything-with-css-align-a-div-text-and-more/ – Charles Roper Oct 23 '22 at 14:08
  • @ArielAlvaro Also, I'd suggest learning CSS before learning React. You're going to find frontend web development _extremely_ difficult if you don't at least learn the basics of CSS first. https://web.dev/learn/css/ – Charles Roper Oct 23 '22 at 14:09