CSS 背景上圖層居中是網頁設計中常見的技巧,可以使頁面效果更加美觀。下面就來介紹怎樣實現背景上圖層居中的效果。
首先,在 HTML 文件中添加一個 div 元素,并設置其樣式,如下所示:
<div class="wrapper"> <div class="content"> <p>這是一個段落。</p> </div> </div> <style> .wrapper { background: url('background.jpg') no-repeat center center fixed; /* 使用 fixed 屬性可以讓背景圖片跟隨頁面滾動 */ background-size: cover; /* 使用 cover 屬性可以讓背景圖片自適應元素大小 */ width: 100%; height: 100%; position: relative; } .content { width: 400px; height: 300px; background-color: #ffffff; opacity: 0.8; position: absolute; top: 50%; left: 50%; margin-top: -150px; margin-left: -200px; /* 其中,400px 和 300px 分別為要顯示內容的寬度和高度, opacity 屬性可以設置背景上圖層的透明度, top、left、margin-top 和 margin-left 可以使 content 元素居中顯示 */ } </style>上述代碼中,.wrapper 元素作為背景元素,使用了一個背景圖片 (background.jpg),使用 fixed 和 cover 屬性讓其自適應瀏覽器大小,并固定在頁面上。 在 .wrapper 元素中,.content 元素作為要顯示的內容,使用了白色背景和 0.8 的透明度設置。其中,position 屬性設置為 absolute,使其相對于 .wrapper 元素定位。top、left、margin-top 和 margin-left 屬性則可以使 .content 元素水平垂直居中。 最終的效果如下: ![示例圖片](https://i.loli.net/2021/11/29/SuoMGiAfKbV7Rd4.png) 以上,就是 CSS 背景上圖層居中的實現方法,希望可以幫助大家更好地掌握這一技巧。