How to align image in react js?

Hi Friends πŸ‘‹,

Welcome To aHoisting!

To align image in center we can use margin: 0 auto; , for right image we can use margin-left: auto; margin-right: 0; , and for align image left we can use margin-left: 0; margin-right: auto;. It will align image in react js.

Today, I am going to show you, how to align image in react js.

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import React, { useState } from 'react';

Step 3: Create a Component.

You can use className="center-image" to align image in react js.

<div>
  <img src={paint} alt="Centered" className="center-image" />
  <img src={painting} alt="Right Aligned" className="right-image" />
  <img src={painte} alt="Left Aligned" className="left-image" />
</div>

Align image example.

The below code is an example of a React. You have to import './img/painting-1.jpg' and use margin: 0 auto; , for right image we can use margin-left: auto; margin-right: 0; , and for align image left we can use margin-left: 0; margin-right: auto;. It will align image in react js.

App.js

import React from 'react';
import paint from './img/painting-1.jpg'; // with import
import painting from './img/painting-4.jpg'; // with import
import painte from './img/painting-3.jpg'; // with import
import './App.css'; 

function AlignedImage() {
  return (
    <div>
      <img src={paint} alt="Centered" className="center-image" />
      <img src={painting} alt="Right Aligned" className="right-image" />
      <img src={painte} alt="Left Aligned" className="left-image" />
    </div>
  );
}

export default AlignedImage;

App.css

.center-image {
  display: block;
  margin: 0 auto;
  width: 200px;
}

.right-image {
  display: block;
  margin-left: auto;
  margin-right: 0;
  width: 200px;
}

.left-image {
  display: block;
  margin-left: 0;
  margin-right: auto;
  width: 200px;
}

In the above code example, I have used the margin-right: auto; and margin-left: 0; to align image in react js.

Check the output of the above code.

React, align, image

All the best πŸ‘