前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >CSS从基础到熟练学习笔记(三)CSS中的5种背景属性(背景颜色、背景图片、固定背景图片等)

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

作者头像
青山师
发布2023-05-04 20:32:22
1.1K0
发布2023-05-04 20:32:22
举报
文章被收录于专栏:IT当时语_青山师_JAVA技术栈

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

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

背景颜色background-color

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

代码语言:javascript
复制
body {
    background-color: lightblue;
}

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

背景图片background-image

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

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

背景图片显示方式background-repeat

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

  • repeat 默认值,水平、垂直均重复
  • repeat-x 水平重复
  • repeat-y 垂直重复
  • no-repeat 不重复,仅仅展示一次
  • initial 将此属性设置为其默认值
  • inherit 从它的父元素继承这个属性 例如:
代码语言:javascript
复制
body {
    background-image: url("https://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 从它的父元素继承这个属性

例如:

代码语言:javascript
复制
body {
    background-image: url("https://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 从它的父元素继承这个属性

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

代码语言:javascript
复制
body {
    background-image: url("https://img-blog.csdn.net/20161118220122095");
    background-repeat: no-repeat;
    background-position: right top
    background-attachment: fixed
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-11-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 背景颜色background-color
  • 背景图片background-image
  • 背景图片显示方式background-repeat
  • 如何定位背景图像background-position
  • 背景图片附着状态background-attachment
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档