CSS一些技巧(一)

81 阅读3分钟

原则:尽量减少代码重复,提高代码可维护性

1.边框

1.半透明边框

background-clip 初始值是 border-box,意味着背景会被元素的边框的外边框裁切掉。如果不希望背景侵入边框所在范围,把它设置为 padding-box,这样就会用内边距的外边沿来把背景裁切掉。

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

2.多重边框

box-shadow支持逗号分隔语法,可以创建任意数量的投影。

background: yellowgreen;
box-shadow: 0 0 0 10px #655,
            0 0 0 15px deeppink,
            0 2px 5px 15px rgba(0,0,0,.6);

3.背景定位

场景:要求偏移量与容器的内边距一致

盒模型: border box(边框的外沿框), padding box(内边框的外沿框),content box(内容区的外沿框)

background-position:top left 默认是指 padding box 的左上角。

background-origin 可以用来改变这种行为,指定为 content-box 后,background-position中的边角就会以内容区的边缘作为基准,背景图片距离边角的偏移量与内边距也会保持一致。

// 正常使用
padding: 10px;
background: url(http://csssecrets.io/images/code-pirate.svg)
	            no-repeat bottom right #58a;
background-position: right 10px bottom 10px;

// 改进后
padding: 10px;
background: url(http://csssecrets.io/images/code-pirate.svg)
	            no-repeat bottom right #58a;
background-origin: content-box;

4.条纹背景

如果第二个色标的位置值为0,则代表和前一个色标位置值相同。

水平:

background: linear-gradient(#fb3 50%, #58a 0);
background-size: 100% 30px;

垂直:

background: linear-gradient(to right, // 或 90deg
                            #fb3 50%, #58a 0);
background-size: 30px 100%;

斜向45:

background: linear-gradient(45deg, 
              #fb3 25%, #58a 0, #58a 50%,
              #fb3 0, #fb3 75%, #58a 0);
background-size: 42.4px 42.4px; // 15*1.414*2

斜向60:

background: repeating-linear-gradient(60deg, 
              #fb3, #fb3 15px,
              #58a 0, #58a 30px);

height: 100%;

同色系条纹:

把最深颜色设为背景色,把半透明的白色条纹叠加在背景色上得到浅色条纹

background: repeating-linear-gradient(30deg, 
              #79b, #79b 15px, #58a 0, #58a 30px);

// 改进后
background: #58a;
background-image: repeating-linear-gradient(30deg, 
              hsla(0,0%,100%,.1), hsla(0,0%,100%,.1) 15px,
              transparent 0, transparent 30px);

2.形状

1.椭圆

border-radius 可以单独指定水平和垂直半径,用 / 分开即可。

width: 8em;
height: 5em;
background: #fb3;
border-radius: 50%; // 或50%/50%

半椭圆:

border-radius 是一个简写属性,展开为: border-top-left-radius、border-top-right-radius、

border-bottom-right-radius、border-bottom-left-radius、

所以可以为四个角提供完全不同的水平和垂直半径。

border-radius:10px / 5px 20px 相当于 10px 10px 10px 10px / 5px 20px 5px 20px

width:8em;
height: 5em;
background: #fb3;
border-radius: 50% / 100% 100% 0 0;

四分之一椭圆:

width:8em;
height: 5em;
background: #fb3;
border-radius: 100% 0 0 0;

2.平行四边形

//正常需要内层元素翻转一下
.button { transform: skewX(45deg); }
.button > div { transform: skewX(-45deg); }

// 不用额外的html元素,使用伪元素
.button {
	position: relative;
}

.button::before {
	content: ''; 
	position: absolute;
	top: 0; right: 0; bottom: 0; left: 0; // 所有偏移量设置为0,以拉伸至宿主元素尺寸
	z-index: -1; // 防止遮住宿主元素内容
	background: #58a;
	transform: skew(45deg);
}

3.菱形

clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%); // 多边形函数,坐标对

参考:

  1. [CSS揭秘]