如何使用 CSS 中的 ::before 偽選擇器放置背景影像?


要使用 ::before 偽選擇器放置背景影像,我們將使用 background-image::before 偽元素。CSS ::before 偽元素用於在選定元素之前新增內容,使用 content 屬性允許插入文字、影像或裝飾性元素,而無需修改 HTML 結構。

在這篇文章中,我們將使用 ::before 偽選擇器在 div 元素內放置背景影像。

使用 ::before 偽選擇器放置背景影像

示例

以下是實現上述步驟的完整示例程式碼。

<html>
<head>
    <title>
        Placing background image using ::before 
        pseudo selectors in CSS
    </title>
    <style>
        .background {
            padding: 15px;
            margin-bottom: 15px;
            width: 500px;
            height: 500px;
            font-size: 20px;
            text-align: center;
        }
        .background::before {
            content: "";
            background-image: url("/html/images/logo.png");
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            background-repeat: no-repeat;
            background-position: center;
            background-size: 100%;
            z-index: -1;
        }
    </style>
</head>
<body>
    <h3>
        To place background image using 
        ::before pseudo selectors in CSS
    </h3>
    <div class="background"> 
        Welcome to the TutorialsPoint..
    </div>
</html>

結論

在這篇文章中,我們使用了 CSS 的 **background-image** 屬性以及 **::before** 偽選擇器在 div 元素中放置背景影像。

更新於: 2024年8月6日

6K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.