《CSS揭秘》读书笔记一

半透明背景

关键在于通过background-clip属性来调整背景的默认行为

1
2
3
4
5
6
7
8
9
10
div {
border: 10px solid hsla(0, 70%, 10%, 0.5);
border-radius: 4px;
background-color: white;
background-clip: padding-box;
max-width: 20rem;
padding: 2rem;
margin: 2rem auto;
}

思考:也可以用box-shadow来实现,优点是可以圆角贴合。

1
2
3
4
5
6
7
8
9
div {
border-radius: 4px;
background-color: white;
box-shadow: 0 0 0 10px hsla(0, 70%, 10%, 0.5);
max-width: 20rem;
padding: 2rem;
margin: 2rem auto;
}

尝试一下

多重边框

box-shadow可层层叠加,达到多层边框的效果。但它不会影响布局,不会受到box-sizing属性的影响,也不会响应鼠标事件,比如悬停或点击。上述问题可通过增加内外边距和inset来解决。
outline只适用于双层“边框”的场景,且边框不一定会贴合border-radius属性产生的圆角。其优点在于样式灵活(dashed等),间距可控(outline-offset)。

1
2
3
4
5
6
7
8
9
10
11
12
13
div {
width: 100px;
height: 60px;
margin: 25px;
background: #9ACD32;
box-shadow: 0 0 0 10px #655,
0 0 0 15px #FF1493,
0 2px 5px 15px rgba(0, 0, 0, .7);
outline: white dashed 1px;
outline-offset: -10px;
}

尝试一下

灵活的背景位置

background-position默认是padding box。
如果想要让它自动地跟着我们设定的内边距走,可以用background-origin: content-box;来解决。
图片位置也可以使用calc()来定位。在calc()函数内部的-和+运算符的两侧需各加一个空白符。

1
2
3
4
5
6
7
8
9
.box {
/*styling*/
max-width: 10em;
min-height: 5em;
padding: 10px;
margin-bottom: 20px;
color: white;
font: 100%/1 sans-serif;
}
1
2
3
4
5
.box1 {
background: url(http://csssecrets.io/images/code-pirate.svg)
no-repeat bottom right #58a;
background-position: right 20px bottom 10px;
}

尝试一下

1
2
3
4
5
.box2 {
background: url(http://csssecrets.io/images/code-pirate.svg)
no-repeat bottom right #58a;
background-origin: content-box;
}

尝试一下

1
2
3
4
5
.box3 {
background: url(http://csssecrets.io/images/code-pirate.svg)
no-repeat bottom right #58a;
background-position: calc(100% - 20px) calc(100% - 10px);
}

尝试一下

区分:background-origin规定背景位置(background-position)的起始点,默认值为padding-box;而background-clip规定背景(图片和背景色)的绘制区域,即裁剪掉区域外的内容,默认值为border-box。可选值图示:
盒模型
盒模型

边框内圆角

方法一:用两个div;
方法二:用box-shadow填补border和outline之间的空缺,其值需小于描边宽度(等于时会渲染异常),大于\\ (\sqrt{2}*r-r \)。

1
2
3
4
5
6
7
8
9
10
11
div {
outline: .6em solid #655;
box-shadow: 0 0 0 .4em #655; /* 阴影尺寸可选圆角值的一半 */
max-width: 10em;
border-radius: .8em;
padding: 1em;
margin: 1em;
background: tan;
font: 100%/1.5 sans-serif;
}

计算图示:阴影尺寸
尝试一下

条纹背景

关键在于渐变色标重合

以下代码可以生成三色水平条纹:

1
2
3
4
5
div {
background: linear-gradient(#fb3 33.3%,
#58a 0, #58a 66.6%, yellowgreen 0);
background-size: 100% 45px;
}

尝试一下
备注:如果我们把第二个色标的位置值设置为0,那它的位置就总是会被浏览器调整为前一个色标的位置值。
垂直条纹:

1
2
3
4
5
div{
background: linear-gradient(to right, /* 或 90deg */
#fb3 50%, #58a 0);
background-size: 30px 100%;
}

尝试一下