如何使用 CSS 中的 ::before 偽選擇器放置背景影像?
要使用 ::before 偽選擇器放置背景影像,我們將使用 background-image 和 ::before 偽元素。CSS ::before 偽元素用於在選定元素之前新增內容,使用 content 屬性允許插入文字、影像或裝飾性元素,而無需修改 HTML 結構。
在這篇文章中,我們將使用 ::before 偽選擇器在 div 元素內放置背景影像。
使用 ::before 偽選擇器放置背景影像
- 我們使用了具有名為 background 的類名的 div 元素,影像將在此處使用。
- 我們使用了 **background** 類來設定背景樣式,它設定了 填充、文字對齊、底部邊距、寬度、高度 和 字型大小。
- 我們使用了 **.background::before** 偽元素,它設定了 background-image,使用 CSS position、top、left、bottom 和 right 屬性定位背景影像,並設定 background-size。
- CSS z-index 屬性有助於使背景文字顯示在影像的前面。
示例
以下是實現上述步驟的完整示例程式碼。
<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 元素中放置背景影像。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP