《css揭秘》笔记(四), 背景定位
发布日期:2022-02-15 02:36:19 浏览次数:6 分类:技术文章

本文共 1370 字,大约阅读时间需要 4 分钟。

《css揭秘》笔记(四), 背景定位

背景定位

难题

有时我们希望图片能和背景之间有一定空隙,而且不仅仅只是针对背景的左上角作为偏移的原点。我们给出以下解决方案。

background-position

background-position的扩展语法允许我们指定背景图片距离任意角的偏移量,只要我们在偏移量前面指定关键字。举例来说,如果想让背景图片跟右边缘保持20px的偏移量,同时跟底边保持10px的偏移量,可以使用如下方式做到:

.box6{
width: 300px; height: 200px; background:url(./img/8.png) no-repeat #58a; background-position: right 20px bottom 10px;}

在这里插入图片描述

在不支持background-position扩展语法的浏览器中,可以把定位值bottom right写进background的简写属性中。

.box6{
width: 300px; height: 200px; background:url(./img/8.png) no-repeat bottom right #58a; background-position: right 20px bottom 10px;}

background-origin方案

在给背景图片设置距离某个角的偏移量时,如果希望偏移量始终与容器的内边距一致,那么在我们修改内边距的值时,每次都需要在三个地方更新这个值,代码就不够DRY。

在默认情况下,background-position是以padding-box为基准的,因此top left默认指的是padding box左上角。background-origin属性可以修改这种基准,默认情况下它的值是padding-box,如果把它的值改成content-box,我们在background-position属性中使用的边角将以内容区边缘作为基准。

我们希望偏移量始终与容器内边距保持一致时,就可以把background-origin的值赋为content-box

.box7{
width: 200px; height: 200px; padding: 10px; background: url(./img/8.png) no-repeat #58a top left; background-origin: content-box;}

在这里插入图片描述

calc()方案

把背景图片定位到距离底边10px且距离右边20px的位置,以背景图片左上角偏移的思路来考虑,其实是希望它能有一个100%-20px的水平偏移量,以及100%-10px的垂直偏移量,而calc()函数允许我们执行此类运算:

.box8{
width: 300px; height: 200px; background: url(./img/8.png) no-repeat #58a; background-position: calc(100% - 20px) calc(100% - 10px);}

在这里插入图片描述

本文是《css揭秘》一书的笔记。

如果本文有侵犯到《css揭秘》作者,请联系我删除。

转载地址:https://blog.csdn.net/PeZXO/article/details/106114901 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:《css揭秘》笔记(二),半透明边框
下一篇:《css揭秘》笔记(五), 条纹背景

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年03月25日 21时43分30秒