一、background-position 概述
CSS background-position 可以用來設置頁面元素(如:div、img 等)背景圖像(background-image)的位置,其基本語法如下:
background-position: [left|center|right] [top|center|bottom];
其中,left|center|right 用於設置水平方向位置,top|center|bottom 用於設置垂直方向位置。
如果只設置一個值,則該值為水平方向位置,垂直方向的位置默認為 center。
使用 background-position 指定背景位置時,水平方向的值決定了背景圖像在背景容器內水平位置的起點,垂直方向的值決定了背景圖像在背景容器內垂直位置的起點。
二、background-position 單位
CSS background-position 的位置單位可以使用絕對單位(如:px、em 等)或相對單位(如:百分比%)。
當使用百分比時,水平方向的值為背景圖像的水平寬度在容器內的位置,垂直方向的值為背景圖像的垂直高度在容器內的位置。
三、background-position 關鍵字
CSS background-position 支持三個關鍵字:left、center、right、top、bottom。
當省略某個位置時,默認值為 center。可以通過使用兩個關鍵字組合,指定背景圖像在水平和垂直方向的位置。
background-position: left top; background-position: right bottom; background-position: center center;
四、background-position 多背景圖像
CSS3 中,background-position 還可以用於設置多背景圖的位置。當使用多背景圖時,需要指定每一個背景圖的位置,依次為:
- 圖片URL
- 定位信息
- 是否重複
每個圖片的定位信息都由兩個數值表示,用逗號分隔,分別用於設置水平方向和垂直方向的位置,如:
.container { background-image: url(image1.png), url(image2.png); background-position: 10px 10px, 20px 20px; background-repeat: no-repeat; }
五、background-position 使用技巧
使用 background-position 可以輕鬆實現以下效果:
- 圖像水平居中或垂直居中
- 圖像位置微調,使元素更加美觀
- 定位多背景圖像
六、示例代碼
.container { background-image: url('background.png'); background-position: center center; background-repeat: no-repeat; }
以上代碼將容器的背景圖像設置為 background.png,並將其位置設置為居中。
.container { background-image: url('background.png'); background-position: 20px 10px; background-repeat: no-repeat; }
以上代碼將容器的背景圖像設置為 background.png,並將其位置微調為距離容器左側 20px,距離容器頂部 10px。
.container { background-image: url('background1.png'), url('background2.png'); background-position: left top, right bottom; background-repeat: no-repeat; }
以上代碼設置了兩個背景圖像:background1.png 和 background2.png,一個定位在頁面左上角,另一個定位在頁面右下角。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/306475.html