理解 background-position

background-position 基础认识

background-position 是css 中定义背景图片位置的一个属性,接受三种类型的值。

  • 关键字:top right bottom left center
  • px 、em 、rem
  • % 百分比

项目中经常用到的值可以参考下图:
background-position

如果提供两个,第一个用于横坐标,第二个用于纵坐标。
如果只提供一个,该值将用于横坐标;纵坐标将默认为50%(即center)。
居中显示时可以使用关键词 “center center “,也可以百分比“50% 50%”。
你还可以这样写:设置背景图距容器某一边距离多少,接受 px ,em,rem 和百分比值

/* 设置4个参数 */
background:url("test.png") no-repeat left 20px top 20px;
/* 设置3个参数 */
background:url("test.png") no-repeat left top 20px;
/* 只设置2个参数 */
background:url("test.png") no-repeat left top;

background-position 中的百分比

我们都知道 background:url("test.png") no-repeat 50% 50%;这样会使背景图片在容器内居中显示。但是为什么呢?这就涉及到背景图片的百分比计算方式了。

w3c 规范关于 background-position

A percentage for the horizontal offset is relative to (width of background positioning area - width of background image). A percentage for the vertical offset is relative to (height of background positioning area - height of background image), where the size of the image is the size given by ‘background-size’.

解释一下,水平方向百分比定位位置等于(背景定位所在容器的宽度减去背景图片宽度百分比)乘以百分比,垂直方向百分比定位位置等于(背景定位所在容器的高度减去背景图片高度百分比)乘以百分比。

看图说话,设置为‘75% 50%’时
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值