CSS Background Position

发布时间:2023-05-12

一、Background Position的概念

在CSS中,我们可以通过background属性来设置元素的背景,background-position是其中一个常用的子属性。background-position用于设置背景图像相对于元素边框的位置,可以通过关键词或者长度单位来设置。

background-position: 50% 50%;
background-position: bottom right;
background-position: 10px 20px;

二、关键词的使用

关键词用于设置背景图像位置,常用的关键词有:

  • top:将背景图像上边缘与元素的上边缘对齐。
  • bottom:将背景图像下边缘与元素的下边缘对齐。
  • left:将背景图像左边缘与元素的左边缘对齐。
  • right:将背景图像右边缘与元素的右边缘对齐。
  • center:将背景图像水平和垂直方向都居中对齐。

三、长度单位的使用

长度单位用于设置背景图像位置的偏移量,可以是百分比或者像素值。(%表示相对于元素的宽度和高度,px表示相对于元素左上角顶点的偏移量)

  • background-position: 50% 50%; /将背景图像水平垂直方向都居中对齐/
  • background-position: 0 0; /将背景图像与元素的左上角对齐/
  • background-position: 100% 100%; /将背景图像与元素的右下角对齐/
  • background-position: 50% 20px; /将背景图像水平居中,垂直偏移量为20px/
  • background-position: 20px 50%; /将背景图像垂直居中,水平偏移量为20px/

四、背景定位的实例

下面是一个示例,展示了不同的背景定位效果是如何实现的:

<style>
  .box1 {
    border: 1px dashed #ccc;
    width: 200px;
    height: 200px;
    background-image: url('background.jpg');
    background-repeat: no-repeat;
    background-position: top left;
  }
  .box2 {
    border: 1px dashed #ccc;
    width: 200px;
    height: 200px;
    background-image: url('background.jpg');
    background-repeat: no-repeat;
    background-position: center center;
  }
  .box3 {
    border: 1px dashed #ccc;
    width: 200px;
    height: 200px;
    background-image: url('background.jpg');
    background-repeat: no-repeat;
    background-position: bottom right;
  }
</style>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>