I’m still a beginner in programming and I’m doing a project to improve knowledge.
I need to insert a div with text on top of an image, I’m trying to recreate the example of the image below:
Half of the div is an image and the other half is text. Can you tell me how I can do that?
Here’s my code I put into codesandbox
JavaScript
x
43
43
1
import React from "react";
2
import "./styles.css";
3
4
export default function App() {
5
return (
6
<div className="App">
7
<h1>Restaurant</h1>
8
<div
9
style={{
10
display: "flex",
11
flexDirection: "column",
12
justifyContent: "baseline",
13
alignItems: "baseline",
14
height: "200px",
15
width: "100%",
16
maxWidth: "300px"
17
}}
18
>
19
<div>
20
<img
21
style={{
22
width: "100%",
23
height: "100%"
24
}}
25
src="https://b.zmtcdn.com/data/collections/271e593eb19475efc39021c6e92603db_1454591396.jpg"
26
alt=""
27
className="img"
28
/>
29
</div>
30
<div className="divText">
31
<span
32
style={{
33
color: "#fff",
34
backgroundColor: "#000"
35
}}
36
>
37
Lorem Ipsum! Lorem Ipsum! Lorem Ipsum!
38
</span>
39
</div>
40
</div>
41
</div>
42
);
43
}
Thank you in advance.
Advertisement
Answer
You have two solutions to set a background image :
use the background properties in CSS
JavaScript
1
4
1
.divText {
2
background-image:url("https://b.zmtcdn.com/data/collections/271e593eb19475efc39021c6e92603db_1454591396.jpg");
3
}
4
use positioning to make a custom layout
JavaScript
1
37
37
1
export default function App() {
2
return (
3
<div className="App">
4
<h1>Restaurant</h1>
5
<div
6
style={{
7
position: "relative",
8
height: "200px",
9
width: "300px"
10
}}
11
>
12
<img
13
style={{
14
width: "100%",
15
height: "100%"
16
}}
17
src="https://b.zmtcdn.com/data/collections/271e593eb19475efc39021c6e92603db_1454591396.jpg"
18
alt=""
19
className="img"
20
/>
21
<div className="divText"
22
style={{
23
position: "absolute",
24
bottom: 0,
25
height: "50%",
26
width: "100%",
27
color: "#fff",
28
backgroundColor: "#000",
29
opacity: 0.7
30
}}>
31
Lorem Ipsum! Lorem Ipsum! Lorem Ipsum!
32
</div>
33
</div>
34
</div>
35
);
36
}
37