如何使用reactJS在图像上创建覆盖



我需要创建一个覆盖整个图像的覆盖层。但我不知道该怎么做。我尝试了CSS上的相对和绝对位置。任何方式,有CSS或没有CSS都可以。

代码在此播放代码中可用。

import React from 'react';
import { Container } from '@mui/material';
import Grid from '@mui/material/Unstable_Grid2';
export function App(props) {
return (
<div className='App'>
<Grid container>
<Grid>
<h1>Do not hide me.</h1>
</Grid>
<Grid>
<Container
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'blue',
}}
>
<img
style={{
maxHeight: 300,
}}
src={
'https://images.unsplash.com/photo-1518133910546-b6c2fb7d79e3?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=735&q=80'
}
alt='img'
></img>
<h1
style={{
position: 'absolute',
left: 0,
top: 0,
opacity: 0.7,
backgroundColor: 'red',
width: 400,
}}
>
Hi there, this text should be only over the image.
</h1>
</Container>
</Grid>
</Grid>
</div>
);
}
// Log to console
console.log('Hello console');

我已经在provide平台中玩过代码,您可以复制以下代码并将其粘贴到操场上。

import React from 'react';
import { Container } from '@mui/material';
import Grid from '@mui/material/Unstable_Grid2';
export function App(props) {
return (
<div className='App'>
<Grid container>
<Grid>
<h1>Do not hide me.</h1>
{/*<another image/>*/}
</Grid>
<Grid>
<Container
style={{
display:"flex",
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'blue',
position: "relative"
}}
>
<img
style={{
maxHeight: 300,
}}
src={
'https://images.unsplash.com/photo-1518133910546-b6c2fb7d79e3?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=735&q=80'
}
alt='img'
></img>
<h1
style={{
position: 'absolute',
top: "-21px",
padding: "0 20px",
opacity: 0.7,
height: "100%",
backgroundColor: 'red',
}}
>
Hi there, this text should be only over the image.
</h1>
</Container>
</Grid>
</Grid>
</div>
);
}
// Log to console
console.log('Hello console');

更改

我已经改变了Container的风格

  • 给它一个relative的位置,使得h1标签的位置相对于container变成绝对的,而不是相对于整个页面

其余更改在h1标签中可见

最新更新