最详细的CSS常用背景属性总结(background-color、background-image、background-repeat、background-position等)


前言

由于自己在学习CSS的过程中会时不时忘记一些CSS背景样式的书写,因此在本文记录了一些常用的CSS背景样式的写法。


一、背景颜色

使用background-color属性设置背景颜色,其属性值与文本color属性值类似,在此不过多阐述,例如:

background-color:red;
background-color:#ff0000;
background-color:rgb(255,0,0);
background-color:transparent;
background-color:rgb(255,0,0,0.3);

注意:
(1)该属性默认值为transparent(透明),即背景色透明
(2)rgb(255,0,0,0.3)也表示设置颜色透明,透明度为0.3。

二、背景图片

使用background-image属性设置背景图片,其参数包括如下:

  • none:默认值,无背景图片
  • url(url):括号内填写图片的相对地址、绝对地址、网址

例如:

background-image: url("imgs/tu.png");
//或者
background-image: url(imgs/tu.png);

注意:
(1)该属性默认值为none。
(2)url()中的地址可以加双引号也可以不加,但是url必需写。

三、背景平铺

背景图片重复显示的效果被称为背景平铺。
使用background-repeat属性设置背景平铺效果,其参数包括如下:

  • repeat:默认值,背景图片在横、纵向上均平铺
  • no-repeat:背景图片不平铺
  • repeat-x:背景图片在横向上平铺
  • repeat-y:背景图片在纵向上平铺

例如:

background-repeat:no-repeat;

注意:
background-image与background-color可以同时使用并显示对应效果,并且背景图片在背景颜色之上,即背景图片会遮住背景颜色。

四、背景图像位置

使用background-position属性设置图片在背景中的位置,语法如下:

background-position:x y;

x、y表示x坐标和y坐标,二者均可用方位名词或精确单位,其参数包括如下:

  • length:百分数或者由浮点数字和单位标识符组成的长度值。
  • position:top/center/bottom/left/right。

例如:
(1)将背景图片垂直居中:

background-position: center center;

(2)将背景图片居中并左移动20px:

background-position: 20px center;

(3)将背景图片固定在页面右下角:

background-position: right bottom;

(4)将背景图片定位到距离左侧30%的位置,距离顶部50像素的位置:

background-position: 30% 50px;

(5)将背景图片定位到距离右侧20像素的位置,距离底部10%的位置:

background-position: right 20px bottom 10%;

注意:
(1)如果x、y均为方位名词,则两个值前后顺序无关,例如left center与center left效果一致。
(2)如果只指定一个方位名词,另一个值省略,则第二个默认居中对齐。但是如果只指定一个left或者right,则表示为x值,y值默认为居中;同样如果只指定一个top或者bottom,则表示为y值,x值默认为居中。

五、背景图像固定(背景附着)

使用background-attachment属性设置背景图像是否固定或者随着页面的其余部分滚动。

  • scroll(默认):背景图片和页面内容一起滚动。
  • fixed:背景图片不随页面滚动而移动,固定在页面的视口中。
  • local:背景图片随着元素内部内容滚动而滚动。

例如:
(1)将背景图片固定在页面顶部

background-attachment: fixed;

(2)指定多个背景图片固定位置

.div1 {
    
    
  background-image: url("img1.jpg"), url("img2.jpg");
  background-position: center top, center bottom;
  background-repeat: no-repeat;
  background-attachment: scroll, fixed;
}

六、背景属性简写

语法:
简写顺序:颜色 地址 平铺 滚动 位置

background:background-color background-image background-repeat background-attachment background-position

例如:

background:transparent url(img.jpg) repeat-y fixed top;

注意: 该属性可以制作后期视差滚动效果。


总结

以上就是有关常用背景样式的笔记内容,希望对各位有所帮助,作者也在学习中,如有解释不清楚或有误的地方,还请各位指正。

猜你喜欢

转载自blog.csdn.net/weixin_56242678/article/details/130517070