Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center an image in ReactJS using css

Tags:

css

image

reactjs

I am using ReactJS create-react-app to build a website. I'm trying to center an image on my homepage horizontally across the screen using css, but it is remaining aligned left.

I have the .jpg being imported into a .js file with a class declaration and it appears on the page but it doesn't follow the class modifications I am making in my index.css file.

//in Cur.js file

import React from 'react';
import Image from 'react-image-resizer';
import cur from './cur.jpg';

function Cur() {

    return (
      <div>
        <Image
          img src={cur} alt="cur" class="center"
          height={350}
          width={700}
        />
      </div>
    );

}

export default Cur;

//in index.css file

.center{
    text-align: center;
    display: block;
    justify-content: center;
    align-items: center;
    margin: auto;
    width: 100%;
  }
like image 312
opposite-people Avatar asked May 14 '19 22:05

opposite-people


People also ask

How do I center align an image in CSS?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.

How do you center something in react JS?

js, set its display property to flex and its alignItems and justifyContent properties to center . The div's content will be horizontally and vertically centered. Copied!

How do I center an image in Javascript?

An <img> element is an inline element (display value of inline-block ). It can be easily centered by adding the text-align: center; CSS property to the parent element that contains it. To center an image using text-align: center; you must place the <img> inside of a block-level element such as a div .


1 Answers

<Image
    img src={cur} alt="cur"
    height={350}
    width={700}
    style={{ alignSelf: 'center' }}
/>

You may separate the inline style, or use styled-components instead

like image 77
nrion Avatar answered Oct 20 '22 05:10

nrion