博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CSS 专业技巧收集
阅读量:6952 次
发布时间:2019-06-27

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

hot3.png

1. 使用:not()为导航添加/取消边框

很多人会这样给导航添加边框,然后给最后一个取消掉:

/* add border */.nav li {  border-right: 1px solid #666;}/* remove border */.nav li:last-child {  border-right: none;}

其实,用CSS的:not()可以简化为下面的代码:

.nav li:not(:last-child) {  border-right: 1px solid #666;}

当然,你也可以使用.nav li + li甚至.nav li:first-child ~ li,但是使用:not()可以使意图更加明确。

2. 给body添加line-height属性

你不需要为<p><h*>分别添加line-height属性,相反的,只需要添加到body上即可:

body {  line-height: 1;}

这样,文本元素就可以很容易的从body继承该属性。

3. 垂直居中

这并不是什么魔法,你可以垂直居中任何元素:

html, body {  height: 100%;  margin: 0;}body {  -webkit-align-items: center;    -ms-flex-align: center;    align-items: center;  display: -webkit-flex;  display: flex;}

还需要其他的?水平居中、垂直居中,在任何时间、任何地方?可以看看CSS-Tricks的。

注意:flexbox 在 IE11 下存在一些。

4. 使用逗号分割列表

使列表看起来像是用逗号分割的:

ul > li:not(:last-child)::after {  content: ",";}

通过:not()伪类去掉最后一个元素后面的逗号。

5. 使用负的nth-child选取元素

使用负的nth-child在 1 到 n 之间选择元素:

li {  display: none;}/* 选择第1到3个元素并显示它们 */li:nth-child(-n+3) {  display: block;}

当然,如果你了解:not()的话,还可以这么做:

li:not(:nth-child(-n+3)) {  display: none;}

 

6. 使用 SVG 作 icon 图标

没什么理由不使用 SVG 作 icon 图标:

.logo {  background: url("logo.svg");}

SVG 对于任何分辨率的缩放效果都很好,并且支持 IE9+所有浏览器,所以,放弃使用 .png、.jpg、.gif文件吧。

注:以下代码对于使用辅助设备上网的用户可以提升可访问性:

.no-svg .icon-only:after {  content: attr(aria-label);}

7. 文本展示优化

有时候字体并不是对于所有设备都显示为最佳效果,所以使用浏览器来帮忙吧:

html {  -moz-osx-font-smoothing: grayscale;  -webkit-font-smoothing: antialiased;  text-rendering: optimizeLegibility;}

8. 使用max-height实现纯CSS幻灯片

使用max-height与超出隐藏实现纯CSS的幻灯片:

.slider ul {  max-height: 0;  overlow: hidden;}.slider:hover ul {  max-height: 1000px;  transition: .3s ease; /* animate to max-height */}

9. 继承box-sizing

box-sizing继承自html

html {  box-sizing: border-box;}*, *:before, *:after {  box-sizing: inherit;}

这使得在插件或者其他组件中修改box-sizing属性变得更加容易。

10. 设置表格相同宽度

.calendar {  table-layout: fixed;}

11. 使用 Flexbox 来避免 Margin Hacks

在做多列布局的时候,可以通过 Flexbox 的space-between属性来避免nth-first-last-child等 hacks:

.list {  display: flex;  justify-content: space-between;}.list .person {  flex-basis: 23%;}

这样,列之间的空白就会被均匀的填满。

13. 对空链接使用属性选择器

<a>中没有文本而href不为空的时候,显示其链接:

a[href^="http"]:empty::before {  content: attr(href);}

浏览器支持

以上技巧支持大部分现代浏览器,如:Chrome、Firefox、Safari、Edge以及IE11。


文章地址:http://info.9iphp.com/a-collection-of-css-protips/

英文原文:https://github.com/AllThingsSmitty/css-protips

转载于:https://my.oschina.net/liuyuantao/blog/704089

你可能感兴趣的文章
搜狐笔试 最大连续递增子段和 关键词连续递增
查看>>
.NET URL 301转向方法的实现
查看>>
新浪微博开放平台链接耗尽的情况分析
查看>>
极限编程的12个实践原则
查看>>
javascript--返回顶部效果
查看>>
C# NamePipe使用小结
查看>>
ZooKeeper Watcher注意事项
查看>>
Linux下清理内存和Cache方法
查看>>
表单元素的外观改变(webkit and IE10)
查看>>
帆软报表学习笔记②——行转列
查看>>
redis应用场景:实现简单计数器-防止刷单
查看>>
两款开发辅助工具介绍
查看>>
python 文件的打开与读取
查看>>
基于ROS的运动识别
查看>>
python 之selectors 实现文件上传下载
查看>>
【hdu - 2568】ACM程序设计期末考试081230
查看>>
C语言基础(一)
查看>>
python处理xml中非法字符的一种思路
查看>>
itextSharp 附pdf文件解析
查看>>
solr6.0.0 + tomcat8 配置问题
查看>>