how to use same style for image imported in code

Viewed 35

I used image in my project imported in .css file and I changed it to have it in code. Unfortunately the style doesn't work the same way. Is there any easy way how to fix them?

<div class="image" />


    
.image {
        background: url('./../images/example.jpg') no-repeat;
        background-size: 100%;
        height: 530px;
    }

to

    <div>
        <img class="image"
             src={`${process.env.PUBLIC_URL}/assets/images/example.jpg`}
             alt="Example"/>
    </div>

.image {
    background-size: 100%;
    height: 530px;
}
2 Answers

You can assign the style to the img tag:

img {
  height: 530px;
  width: 100%;
}

img {
  height: 530px;
  width: 100%;
}
<div>
  <img class="image"
    src="https://via.placeholder.com/200"
    alt="Example"/>
</div>

Put the image URL in a style attribute

Your CSS code can stay mostly the same. See below.
The trick is to not write an img tag, but give the div a style attribute with a background-image:

<div class="image"
     style="background-image:url({`${process.env.PUBLIC_URL}/assets/images/example.jpg`});">
</div>

CSS

.image {
    background-repeat: no-repeat;
    background-size: 100%;
    height: 530px;
}

Here is a demonstration with an example image:

.image {
    background-repeat: no-repeat;
    background-size: 100%;
    height: 530px;
}
    <div class="image" style="background-image:url(https://via.placeholder.com/200);">
</div>

Related