16个CSS常用技巧的代码片段
1、利用 CSS穿透覆盖默认样式
img { pointer-events: none;}
2、实现自定义原生 select 控件的样式
3、文本溢出处理
//单行
.single { overflow: hidden; white-space: nowrap; text-overflow: ellipsis;}
//多行
.more { display: -webkit-box !important; overflow: hidden; text-overflow: ellipsis; work-break: break-all; -webkit-box-orient: vertical; -webkit-line-clamp:
2; //指定行数}
4、开启弹性滚动
body { overflow: scroll; -webkit-overflow-scrolling: touch;}
5、 一像素边框设置
.folder li { position: relative; padding: 5px;}.folder li + li:before { position: absolute; top: -1px; left: 0; content: " "; width: 100%; height: 1px; border-top: 1px solid #ccc; -webkit-transform: scaleY(0.5);}
6、防止鼠标选中事件
<div class="mask" onselectstart="return false"></div><div class="link"> <a href="javascrip;;">登录</a></div>
7、给动态添加的元素绑定事件
$(document).on("click", ".large", slide); //jq中的写法//第一个参数表示的是对应事件,第二个是需要绑定事件的元素的id或class,第三个是绑定的对应的事件函数名
8、兼容 IE 浏览器的透明度处理
.ui { width: 100%; height: 100%; opacity: 0.4; filter: Alpha(opacity=40); //兼容IE浏览器的处理}
9、常用的全屏居中 js 函数
//获取元素function getElement(ele) { return document.getElementById(ele);}//自动居中函数function autoCenter(el) { var bodyX = document.documentElement.offsetWidth || document.body.offsetWidth; var bodyY = document.documentElement.offsetHeight || document.body.offsetHeight; var elementX = el.offsetWidth; var elementY = el.offsetHeight; el.style.left = (bodyX - elementX) / 2 + "px"; el.style.top = (bodyY - elementY) / 2 + "px";}
10、常用的全屏居中 css 函数
body { height: 100vh; text-align: center; line-height: 100vh;}
11、在输入框输入完内容并按回车的时候进行判断
<input type="textbox" id="textbox1" onkeypress="CheckInfo" /> <script language="JavaScript" type="text/JavaScript"> function CheckInfo(){ if (event.keyCode==13) { alert(textbox1.text); } }</script>
12、chrome 调试快捷键
13、创建剪切动画
.animate { width: 200px; height: 200px; background: #000; animation: 1s clip;}@keyframes clip { 0% { clip-path: inset(0 0 0 0); } 100% { clip-path: inset(0 100% 100% 0); }}
.clip { clip-path: polygon(0 100%, 50% 0, 100% 100%, 0 30%, 100% 30%); /* 多边形 */ clip-path: circle(30px at 35px 35px); /* 圆形 */ clip-path: ellipse(30px 25px at 35px 35px); /* 椭圆 */}
14、优化动画性能
.animate { width: 200px; height: 200px; background: #000; animation: 1s clip; will-change: clip-path;}@keyframes clip { 0% { clip-path: inset(0 0 0 0); } 100% { clip-path: inset(0 100% 100% 0); }}
15、实现长宽比
/* 1:1 */.container { width: 200px;}.container:after { display: block; content: ' '; padding-top: 100%;}/* 16:9 */.container { width: 200px;}.container:after { display: block; content: ' '; padding-top: calc(100% * 9 / 16);}
16、垂直居中
- dislay: inline-block
- top: 50% + transform: tranlsateY(-50%)
- display: flex
- 子元素需要文字截断,为了兼容4.X的Android浏览器,必须使用其他方式(一般是transform)
- 子元素需要多行布局,4.x的Android不支持flex-wrap,不能多行布局
文章链接:https://www.lilianhua.com/16-code-snippets-of-common-css-skills.html

