Reputation: 591
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.
Can anyone tell me what I am doing wrong?
Upvotes: 11
Views: 13963
Reputation: 4325
It's very important to set height, but not in %
Example provided by Yuval is correct and worked fine.
.bg {
height: 300px;
width: 300px;
}
Upvotes: 0
Reputation: 1
Have you tried switching from
background: url('/img/bg.jpg');
to
background-image: url('/img/bg.jpg');
Upvotes: 0
Reputation: 1
Place the img folder in public folder
.css
background: url('/img/bg.jpg');
or
.js
var logo=require("../img/Logo.svg");
<img src={logo} alt="logo"/>
Upvotes: 0
Reputation: 66
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.
Upvotes: 1
Reputation: 291
background-size: contain;
Not sure what the image is, but this would size the image to fit the current div height defined by the text.
Upvotes: 0
Reputation: 1367
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.
Upvotes: 1
Reputation: 448
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.
Upvotes: 1