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:
Can anyone tell me what I am doing wrong?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With