Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js css class background image not visible

I have added a class in react component.
CSS file:

.bg{
   background: url('../img/bg.jpg');
   border: 2px solid black;
}

React render method:

  render() {
   return (
    <div>
      <div className="bg">
       Hey This
      </div>
    </div>
  );
}

The browser shows the border and loads the image but image is not visible.

The screenshot is as follows: enter image description here

Can anyone tell me what I am doing wrong?

like image 305
Mahesh Haldar Avatar asked Feb 08 '16 20:02

Mahesh Haldar


3 Answers

Try changing the background to background-image. Also give the bg class a height and a width. Then finally specify background-size to probably cover. An example would look like

.bg {
  background-image: url('../img/bg.jpg');
  background-size: cover;
  border: 2px solid black;
  height: 300px;
  width: 300px;
}

This should work as I have tried it.

like image 68
hajorg Avatar answered Sep 22 '22 04:09

hajorg


Your .bg div is currently of size 0x0 px, this is why the image is not showing. Specify a width and a height to see the image.

For example:

.bg {
    height: 300px;
    width: 300px;
}

Or more preferably use 100% to have the entire image fit in the div.

.bg {
    height: 100%;
    width: 100%;
}

As a side note: make sure your background image is not too large and takes much time to load. Large background image size can lead to very bad user experience. Consider using a png image, small image with the repeat attribute, or an svg.

like image 44
Yuval Avatar answered Sep 22 '22 04:09

Yuval


This is most likely happening because div.bg does not have a height specified. Because of this, its height fits the text content exactly.

Background images of any size have no affect on the sizing of their parent element. If your goal is to be able to see the entire image, you need to specify a height for div.bg that matches the height of the original image.

like image 40
sighrobot Avatar answered Sep 22 '22 04:09

sighrobot