Skip to content
Advertisement

How to put div over image with HTML and CSS?

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:

enter image description here

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

import React from "react";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <h1>Restaurant</h1>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          justifyContent: "baseline",
          alignItems: "baseline",
          height: "200px",
          width: "100%",
          maxWidth: "300px"
        }}
      >
        <div>
          <img
            style={{
              width: "100%",
              height: "100%"
            }}
            src="https://b.zmtcdn.com/data/collections/271e593eb19475efc39021c6e92603db_1454591396.jpg"
            alt=""
            className="img"
          />
        </div>
        <div className="divText">
          <span
            style={{
              color: "#fff",
              backgroundColor: "#000"
            }}
          >
            Lorem Ipsum! Lorem Ipsum! Lorem Ipsum!
          </span>
        </div>
      </div>
    </div>
  );
}

Thank you in advance.

Advertisement

Answer

You have two solutions to set a background image :

use the background properties in CSS

.divText {
  background-image:url("https://b.zmtcdn.com/data/collections/271e593eb19475efc39021c6e92603db_1454591396.jpg");
}

use positioning to make a custom layout

export default function App() {
  return (
    <div className="App">
      <h1>Restaurant</h1>
      <div
        style={{
          position: "relative",
          height: "200px",
          width: "300px"
        }}
      >
        <img
          style={{
            width: "100%",
            height: "100%"
          }}
          src="https://b.zmtcdn.com/data/collections/271e593eb19475efc39021c6e92603db_1454591396.jpg"
          alt=""
          className="img"
        />
        <div className="divText"
          style={{
            position: "absolute",
            bottom: 0,
            height: "50%",
            width: "100%",
            color: "#fff",
            backgroundColor: "#000",
            opacity: 0.7
          }}>
            Lorem Ipsum! Lorem Ipsum! Lorem Ipsum!
        </div>
      </div>
    </div>
  );
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement