Reputation: 83
In a React functional component I'm trying to add an image and then add an opaque overlay on top if it.
I've tried the following code sections in my css and react.js files:
In the css file:
.Image {
background-color: #2F5596;
}
.Overlay {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
height: 100%;
background-color: 'rgba(0, 0, 0, 0.5)';
}
In the js file:
import logo from '../../assets/images/WhiteLettering_BlueBackground/WhiteLettering_BlueBackground_256.png';
import classes from './Layout.css';
const layout = (props) => {
return (
<div className={classes.Image}>
<img src={logo} className={classes.Overlay} />
</div>
)
}
export default layout;
While the "logo" shows up perfectly with the blueish background, the opaque overlay does not appear.
Any help would be greatly appreciated.
Thanks,
Upvotes: 2
Views: 5730
Reputation: 191916
Use a an absolutely positioned pseudo-element (::before
), that will appear on top of the image:
const logo = 'https://picsum.photos/1200/1200';
const Layout = (props) => (
<div className="container">
<img src={logo} className="image" />
</div>
)
ReactDOM.render(
<Layout />,
root
)
.container {
position: relative;
background: #2F5596;
}
.container::before {
position: absolute;
display: block;
transform: translateX(-50%);
left: 50%;
width: 50%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
content: '';
}
.image {
object-fit: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 2