CSS_background-position用法

這一篇要介紹:background-position 的多種設定方式

教學網站

https://www.w3schools.com/cssref/pr_background-position.asp

我的codepen練習:
https://codepen.io/saffranwang/pen/mYJJbR

Definition and Usage

background-position是用來設定背景圖片的「起始位置 starting position」

背景圖的「預設值」:

  • 置於容器的左上角
  • 於「水平、垂直」方向都會 repeat

CSS Syntax

1
background-position: value;

value 可以填入的值:

第一種:方位的 keyword

  • left top
  • left center
  • left bottom
  • right top
  • right center
  • right bottom
  • center top
  • center center
  • center bottom

如果只有填入一個值,另一個值就會被設定為「center」

範例 css:

1
2
3
4
5
6
7
8
.box{
width: 400px;
height: 400px;
border: 2px solid #000;
background-image: url(https://i.ibb.co/RDFV9t6/iconfinder-instagram-386648.png);
background-repeat: no-repeat;
background-position: right bottom;
}

第二種:x% y%

  • 第一個值是「水平方向」的位置,第二個值是「垂直方向」的位置
  • 最左上角是「0% 0%」,最右下角是「100% 100%
  • 如果只有填入一個值,另一個值就會被設定為「50%」
  • 預設值為「0% 0%

範例 css:

1
2
3
4
5
6
7
8
.box{
width: 400px;
height: 400px;
border: 2px solid #000;
background-image: url(https://i.ibb.co/RDFV9t6/iconfinder-instagram-386648.png);
background-repeat: no-repeat;
background-position: 25% 75%;
}

第三種:xpos ypos

  • 第一個值是「水平方向」的位置,第二個值是「垂直方向」的位置
  • 最左上角是「0 0
  • 單位可以是 pixels (0px 0px) 或是其他的 CSS units
  • 如果只有填入一個值,另一個值就會被設定為「50%」
  • 「百分比%」和「方位keywords」可以混搭著用

範例 css:

1
2
3
4
5
6
7
8
.box{
width: 400px;
height: 400px;
border: 2px solid #000;
background-image: url(https://i.ibb.co/RDFV9t6/iconfinder-instagram-386648.png);
background-repeat: no-repeat;
background-position: 50px 100px;
}

更多範例

背景圖置中於上方

css:

1
2
3
4
5
6
7
8
.box{
width: 400px;
height: 400px;
border: 2px solid #000;
background-image: url(https://i.ibb.co/RDFV9t6/iconfinder-instagram-386648.png);
background-repeat: no-repeat;
background-position: center top;
}

下方要完整呈現

css:

1
2
3
4
5
6
7
8
9
10
.box{
width: 500px;
height: 300px;
border: 2px solid #000;
background-image: url(https://i.ibb.co/TRgySw0/jquery-lightbox.png);
background-repeat: no-repeat;
/* 背景圖的下方要完整呈現 */
background-size: cover;
background-position: bottom center;
}
  • 背景圖的下方完整呈現
1
2
background-size: cover;
background-position: bottom center;
  • 上方被裁切沒關係