《CSS揭秘》 |背景与边框

本章例子:https://codepen.io/sanhuamao1/pen/YzNOZqY

1 透明边框

你可能会这样写:

border: 10px solid hsla(0,0%,100%,.5);
background: white;

然而,半透明白色边框处透出了自己的纯白实色背景,而并没有半透明效果。下面的写法会让背景限制在内边框(padding)内,让实色背景不影响半透明边框(border)。

border: 10px solid hsla(0,0%,100%,.5);
background: white;
background-clip: padding-box;

指定背景绘制区域:
background-clip: border-box|padding-box|content-box;

  • border-box 默认值。背景绘制在边框方框内(剪切成边框方框)。
  • padding-box 背景绘制在衬距方框内(剪切成衬距方框)。
  • content-box 背景绘制在内容方框内(剪切成内容方框)

2 多重边框

box-shadow

box-shadow它支持逗号分隔语法,所以可以创建任意数量的投影。它们是层层叠加的,第一层投影位于最顶
层,依次类推。因此,你需要按此规律调整扩张半径:

background: antiquewhite;
box-shadow: 0 0 0 10px #655, 0 0 0 15px deeppink;

【注意】投影跟边框不完全一致,因为它不会影响布局,也不会受到 box-sizing 属性的影响。当然,你可以通过内边距或外边距来额外模拟出边框所需要占据的空间。 上述方法所创建出的假“边框”出现在元素的外圈。它不会响应鼠标事件;你可以给box-shadow 属性加上 inset 关键字,来使投影绘制在元素的内圈


盒子阴影:box-shadow: h-shadow v-shadow blur spread color inset;

  • h-shadow 必需的。水平阴影的位置。允许负
  • v-shadow 必需的。垂直阴影的位置。允许负值
  • blur 可选。模糊距离
  • spread 可选。阴影的大小
  • color 可选。阴影的颜色。在CSS颜色值寻找颜色值的完整列表
  • inset 可选。从外层的阴影(开始时)改变阴影内侧阴影

outline

你可能只需要两层边框,那只需先设置一层常规边框,再加上 outline(描边)来产生第二层的边框。

background: antiquewhite;
border: 10px solid #655;
outline: 5px solid deeppink;

此外,boxshadow只能模拟实现边框,而outline更灵活,可配合outline-offset实现缝边效果:

background: #655;
outline: 1px dashed white;
outline-offset:-8px;
border:15px solid #655;

【注意】:

  • 它只适用于双层“边框”的场景
  • 边框不一定会贴合 border-radius 属性产生的圆角

3 背景定位

背景定位

background-position

background: url("tree.png") no-repeat #58a;
background-position: right 20px bottom 10px; /*指定偏移位置*/

当偏移量与容器的内边距一致。如果使用position,那么会写成这样。这样写不太ok,因为每次改动内边距时,都需要在三个地方更新这个值:

padding: 10px;
background: url("tree.png") no-repeat #58a;
background-position: right 10px bottom 10px;

background-origin

上面的问题可以由这个属性解决。让它自动地跟着我们设定的内边距走,不用另外声明偏移量的值:

padding: 10px;
background: url("tree.png") no-repeat #58a bottom right; /* 或 100% 100% */
background-origin: content-box;

calc()

background: url("tree.png") no-repeat #58a;
background-position: calc(100% - 20px) calc(100% - 10px);

4 边框内圆角

一般情况下我们可能要创建两个元素实现该效果,现可尝试以下办法:

background: tan;
border-radius: .8em;
box-shadow: 0 0 0 .6em #655; /*会继承圆角*/
outline: .6em solid #655;/*填补圆角空隙 使成为矩形*/
posted @ 2021-04-19 15:24  sanhuamao  阅读(128)  评论(0编辑  收藏  举报