0

When I added absolute to the image, the image was centerd.
I want to center an image tag and a p tag with a div tag, and I want the div tag to be centered with absolute, but it is not centered

import { FunctionComponent } from 'react';

const Index: FunctionComponent = () => {
  return (
    <>
        <img
          src="profile.svg"
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            margin: 'auto',
          }}
        />
    </>
  );
};

export default Index;

const Index: FunctionComponent = () => {
  return (
    <>
      <div
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          margin: 'auto',
        }}
      >
        <img src="profile.svg" />
        <p>name</p>
      </div>
    </>
  );
};

export default Index;
  • if you want to center vertical and horizontally to the screen, you should use position: fixed;``position: absolute will position an item to the relative parent or the entire website. However absoltue or fixed positing is a bad way to center an element. Its way easier and responsive to do this with the use of flexbox. – tacoshy Mar 11 '21 at 12:50
  • I'm using absolute because I want to put the front-most div in the middle. – user15375616 Mar 12 '21 at 11:07
  • doesnt explain the use of `position: absolute`. There plenty other ways to center elements. if you want to center of the screen not the website, you need to use `position: fixed` – tacoshy Mar 12 '21 at 11:11
  • I want to make a div tag the size of a child element, but the size of the div tag spreads across the screen. – user15375616 Mar 12 '21 at 11:13

2 Answers2

0

try to give your div a with and then do this:

width: 80vw;
left: 50%;
margin-left: -40vw;
-1

maybe give the div a position relative or margin 0 auto or something like

display: flex;
  align-items: center;
  justify-content: center
Daniel
  • 1
  • 1