html背景定位方式,CSS揭秘之《灵活的背景定位》

针对容器某个角对背景图片做偏移定位

现在就假设想针对容器右下角右侧20px偏移,底部10px偏移

有如下几种方式

1、原理设置透明边框

div {

background: url(../images/code-pirate.svg) no-repeat 100% 100% #58a;

border-right: 20px solid transparent;

border-bottom: 10px solid transparent;

}

2、给background-position指定right bottom值

备注:因为css3中background-position 属性已经得到扩展, 它允许我们指定背景图片距离任

意角的偏移量, 只要我们在偏移量前面指定关键字

div {

background: url(../images/code-pirate.svg) no-repeat #58a;

background-position: right 20px bottom 10px;

/*上面一句写成这样也是同样的效果

background-position: bottom 10px right 20px ;*/

}

3、针对第二种方式实现的回退方案

div {

background: url(../images/code-pirate.svg) no-repeat bottom right #58a;

background-position: right 20px bottom 10px;

}

具体效果见 链接

4、使用padding加background-origin

备注:此方案适用于偏移量与容器的内边距一致,默认情况下background-position 是以 padding box 为准的,所以background-position:top left; top left是以 padding box 的左上角,之所以默认值是padding-box这样边框才不会遮挡背景图片

div {

padding: 10px 20px;

background: url(../images/code-pirate.svg) no-repeat #58a bottom right;

/* 或 100% 100% */

background-origin: content-box;

}

具体效果见链接

5、使用透明边框加background-origin

div {

padding: 0;

border-right: 20px solid transparent;

border-bottom: 10px solid transparent;

background: url(../images/code-pirate.svg) no-repeat #58a bottom right;

/* 或 100% 100% */

background-origin: padding-box;

}

6、使用calc计算宽高

div {

background: url(../images/code-pirate.svg) no-repeat #58a;

background-position: calc(100% - 20px) calc(100% - 10px);

}

具体效果见链接

备注:以前只知道calc中的运算符需要两侧各加一个空白符,否则会产生解析错误,现在知道真正的原因是为了向前兼容,在未来,在 calc() 内部可能会允许使用关键字,而这些关键字可能会含连字符(即减号)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值