CSS从基础到熟练学习笔记(三)CSS中的5种背景属性(背景颜色、背景图片、固定背景图片等)

来源:互联网 发布:javascript 字符转数字 编辑:程序博客网 时间:2024/04/28 20:11

CSS背景属性用于定义元素的背景效果,常用的有5种背景属性:背景颜色、背景图片、背景图片重复展示的方式、背景附着的方式以及背景位置

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

背景颜色background-color

(本文章分享在CSDN平台,更多精彩请阅读 东陆之滇的csdn博客:http://blog.csdn.net/zixiao217 ,如在其他平台看到此文可能会出现内容不完整的现象,请移至东陆之滇http://blog.csdn.NET/zixiao217查看原文)

CSS中可以通过background-color属性指定元素的背景颜色,例如指定body元素的背景颜色:

body {    background-color: lightblue;}

颜色的表示方式也有3中,具体可参见RGB颜色对照表以及详细介绍CSS中的三种颜色表示方式

背景图片background-image

CSS通过background-image属性指定元素的背景图片。
语法background-image: url| none| initial| inherit;
属性值:

  • url(‘URL’) 背景图片的地址,多张背景图片可以使用逗号隔开
  • none 默认值,无背景
  • initial 将此属性设置为其默认值
  • inherit 从它的父元素继承这个属性
    例如:
body {    background-image: url("http://img.blog.csdn.net/20161118220122095");}

背景图片显示方式background-repeat

CSS通过background-repeat属性指定背景图片的展示方式。
属性值:

  • repeat 默认值,水平、垂直均重复
  • repeat-x 水平重复
  • repeat-y 垂直重复
  • no-repeat 不重复,仅仅展示一次
  • initial 将此属性设置为其默认值
  • inherit 从它的父元素继承这个属性
    例如:
body {    background-image: url("http://img.blog.csdn.net/20161118220122095");    background-repeat: no-repeat;}

如何定位背景图像background-position

CSS可以通过background-position属性指定背景图片的位置。默认值为0% 0%

属性值:

  • left top 左上角,如果仅仅制定一个值,则另一个值默认为center,即left <=> left center。类似的方式还有left centerleft bottomright topright centerright bottomcenter topcenter centercenter bottom
  • x% y% 第一个值代表水平位置,第二个值代表垂直位置。例如:left corner 等价于0% 0%。right bottom 等价于100% 100%。如果仅仅制定一个值,则另一个默认为50%。 该属性默认值为0% 0%。
  • Xpx Ypx 也可以使用像素指定位置,或者像素值和百分比值混合使用
  • initial 将此属性设置为其默认值
  • inherit 从它的父元素继承这个属性

例如:

body {    background-image: url("http://img.blog.csdn.net/20161118220122095");    background-repeat: no-repeat;    background-position: center}

背景图片附着状态background-attachment

CSS使用 background-attachment属性指明 背景附件属性来设置背景图像是否是固定的或是与页面的其余部分一起滚动。
语法: background-attachment: scroll| fixed| local| initial| inherit;
属性值:

  • scroll 随元素一起滚动,默认值。如果背景在页顶,则页面拉到页脚时看不到页顶元素也就看不到图片了。
  • fixed 固定背景背景图片,使用该值时,背景图片会一直在固定位置显示。
  • local 背景沿元素的内容滚动
  • initial 将此属性设置为其默认值
  • inherit 从它的父元素继承这个属性

例如,背景图片一直显示在右上角:

body {    background-image: url("http://img.blog.csdn.net/20161118220122095");    background-repeat: no-repeat;    background-position: right top    background-attachment: fixed}
0 0