Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Apply Inline Style and className to Same Element

I have a div that has a decently long list of styles that would look ridiculous to apply inline, however, the div takes a parameter of a background image url that will change upon updating state.

Styled inline, my element looks like this:

      <div style={{width: 55,
                  height: 55,
                  position: 'fixed',
                  borderRadius: '50%',
                  bottom: 130,
                  zIndex: 200,
                  backgroundImage: `url(${this.state.avatar})`}}>

However, when I do this, my background image disappears completely:

<div className="avatar" style={{backgroundImage: `url(${this.state.avatar})`}}>

What is the fix here?

like image 456
Jessie Richardson Avatar asked Jan 29 '23 15:01

Jessie Richardson


2 Answers

I created a sample project with create-react-app and used the following code, it's working for me:

App.js:

import React, {Component} from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {avatar: 'https://www.gstatic.com/webp/gallery3/1.png'}
  }

  render() {
    return (
      <div className="avatar" style={{backgroundImage: `url(${this.state.avatar})`}}>
        something here...
      </div>
    );
  }
}

export default App;

And the App.css:

.avatar {
  width: 500px;
  height: 500px;
  position: fixed;
  border-radius: 50%;
  bottom: 130px;
  z-index: 200;
}
like image 153
salman.zare Avatar answered Jan 31 '23 09:01

salman.zare


@salman.zare 's answer is 100% correct to the question I had posted, however, the problem I had turned out not to have anything to do with combining a className and an inline style. The issue was that my div container was too small for the image, 50px. Here is was I added to make it work: background-size: contain;

So:

.avatar {
  width: 50px;
  height: 50px;
  position: fixed;
  border-radius: 50%;
  bottom: 130px;
  z-index: 200;
  background-size: contain;
}

This also works and will not cut-off the bottom of the image if using no-repeat: background-size: 100% 100%;

.avatar {
  width: 55px;
  height: 55px;
  position: fixed;
  border-radius: 50%;
  bottom: 130px;
  z-index: 200;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
like image 44
Jessie Richardson Avatar answered Jan 31 '23 08:01

Jessie Richardson