Open In App

How to set the height and width of background image inline style in react?

Last Updated : 16 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In React, one can create an object with styling information like background image, height, width, etc and refer to the object in the style attribute in the HTML element. Since the inline CSS is written in a JavaScript object, properties with two names, like background-color, must be written with camel case syntax.

Syntax :

class MyHeader extends React.Component {
  render() {
    const mystyle = {
      backgroundColor: "white",
     // CSS CODE
     };
    return (
      <div>
      <h1 style={mystyle}>Hello Style!</h1>
      // All styling define in mystyle 
      // object will applied to h1 element.
      </div>
    );
  }
}

Example 1: Set width and height of background image in div element to 100% and 200px .

Javascript




import React from 'react';
import './App.css';
  
function App() {
  const myStyle={
    backgroundImage:"url(" +
    width:'100%',
    height:'200px',
    };
  return (
    <div style={myStyle}>
     <h1 style={{color:'green'}}> 
       Geeks For Geeks 
     </h1>
     <p style={{color:'white'}}> 
       Set height and width of background
       image inline style react. 
     </p>
  
    </div>
  );
}
export default App;


Output: Here, all style define in myStyle object is applicable to the div element. One can check the width and height of the background image in the div element is 100% and 200px. 

Example 2: Set width and height of background image in div element to 20% and 200px .

Javascript




import React from 'react';
import './App.css';
  
function App() {
  const myStyle={
    backgroundImage:"url(" +
    width:'20%',
    height:'200px',
    };
  return (
    <div style={myStyle}>
     <h1 style={{color:'green'}}> 
       Geeks For Geeks 
     </h1>
     <p style={{color:'white'}}> 
       Set height and width of background image
       inline style react. 
    </p>
  
    </div>
  );
}
export default App;


Output: Here, all style define in myStyle object is applicable to the div element. One can check the width and height of the background image in the div element is 20% and 200px. 

Note: Similarly, one can define many other CSS styles in an object and call the object in the style attribute of the respective HTML element. All the CSS styles defined in the object will be applied to that particular HTML element as shown in the above example.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads