背景定位

当图像作为背景和文本显示在同一个位置时,为了页面排版更优美、更易于文本的阅读,可以使用background-position属性改变图像在背景中的位置:

1
2
3
4
5
6
body {
/*设置背景图片*/
background-image: url("https://gitee.com/chuyuxuan/tuc/raw/master/CSS/sun2.jpg");
background-repeat: no-repeat;
background-position: right top;
}

显示效果如图:

本例中,设置right top代表放置在元素内边距区的右上角。

对于具体位置,大家可以使用如下关键字的组合:

属性值
top left
top center
top right
center left
center center
center right
bottom left
bottom center
bottom right
如果值定义了一个关键词,那么第二个值将是center。当然也可以使用百分比和长度值.

背景关联

当页面较长时,滚动页面,背景图像也会随之滚动。当文档滚动到超过图像的位置时,图像就会消失。如果想要背景图像不随页面滚动而改变位置。可以使用background-attachment属性,将其值设置为fixed

1
2
3
4
5
6
body {
background-image: url("https://www.educoder.net/attachments/download/211104");
background-repeat: no-repeat;
background-attachment: fixed;
}

简写背景

为了简化这些属性的书写,我们可以将这些属性合并在同一个属性中。

例如:

1
2
3
body {
background:#ffffff url("./Assert/sun.jpg") no-repeat right top;
}

使用简写属性时,属性值的顺序为:

1
2
3
4
5
6
7
8
9
background-color

background-image

background-repeat

background-attachment

background-position

以上属性无需全部使用,可以按照页面设置使用。