簡體   English   中英

向圖像添加疊加背景未正確響應

[英]Adding an overlay background to image not responding properly

目前,我正在嘗試在我的圖像上覆蓋一層以使其更暗並在其上添加文字。 我為我的圖像和疊加層使用了絕對定位,但由於某種原因,疊加層占據了我的 window 的整個空間並位於我的文本上方。 我希望它看起來像這樣:

在此處輸入圖像描述

代碼沙盒: https://codesandbox.io/s/amazing-mendeleev-gohz7?file=/src/App.tsx

代碼:

<div className="container" style={{ padding: "30px" }}>
        <img style={{ borderRadius: "10px" }} src="dubai.png"></img>
        <div
          style={{
            background: "rgba(0, 0, 0, 0.5)",
            width: "100%",
            height: "100%",
            zIndex: 1,
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)"
          }}
        ></div>
        <div
          style={{
            color: "#fff",
            position: "absolute",
            top: "20%",
            left: "50%",
            transform: "translate(-50%, -100%)",
            fontFamily: "Roboto",
            width: "100%"
          }}
        >
          <div style={{ fontSize: "35px", textAlign: "center", zIndex: 200 }}>
            DUBAI UAE
          </div>
        </div>
      </div>

你需要 position 你的覆蓋相對於它的父級。

然后,您的父母設置了 padding:10px 。 這意味着圖像將變小(不會覆蓋整個 div )寬度為 20 像素,高度為 20 像素。 但是疊加層將覆蓋整個 div。 從那里您可以在評論中看到“圖像周圍的邊框”,如 state 所示。 實際上它只是parent div上的10px填充所形成的空白空間。

所以,你必須讓你的疊加層更小才能不超過圖像。 為此,您應該對疊加層的寬度和高度使用calc(100% - 20px)

文本的定位和 zIndex 也必須更改。 看看這里https://codesandbox.io/s/interesting-tree-p4vwp?file=/src/App.tsx

下面的代碼

import "./styles.css";
import Head from "next/head";

export default function App() {
  return (
    <>
      <div
        className="container"
        style={{ padding: "10px", position: "relative" }}
      >
        <img
          style={{ borderRadius: "10px", width: "100%", height: "auto" }}
          src="dubai.png"
        />
        <div
          style={{
            background: "rgba(0, 0, 0, 0.5)",
            width: "calc(100% - 20px)",
            height: "calc(100% - 20px)",
            zIndex: 1,
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            borderRadius: "10px"
          }}
        ></div>
        <div
          style={{
            color: "#fff",
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            fontFamily: "Roboto",
            width: "100%",
            zIndex: 2
          }}
        >
          <div style={{ fontSize: "35px", textAlign: "center", zIndex: 200     }}>
            DUBAI UAE
          </div>
        </div>
      </div>
    </>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM