CSS高级技巧

使用:not()在菜单上添加/取消边框


不少人会这样给导航添加边框,而后给最后一个取消掉:html

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

其实,用CSS3:not()能够简化为下面的代码:web

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

固然,你也可使用.nav li + li甚至.nav li:first-child ~ li,可是使用:not()可使意图更加明确
全部主流浏览器均支持:not选择器,除了IE8及更早的版本浏览器

body添加line-height属性


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

body {
  line-height: 1;
}

这样,文本元素就能够很容易的从body继承该属性svg

垂直居中


能够垂直居中任何元素:布局

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

注:flexbox在IE11下存在一些bug字体

使用逗号分割列表


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

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

经过:not()伪类去掉最后一个元素后面的逗号优化

使用负的nth-child选取元素


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

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

固然,若是你了解:not()的话,还能够这么作:

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

使用SVG做icon图标


没什么理由不使用SVGicon图标:

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

SVG对于任何分辨率的缩放效果都很好,而且支持 IE9+全部浏览器,因此,放弃使用png、jpg、gif文件吧
注:如下代码对于使用辅助设备上网的用户能够提高可访问性:

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

优化显示文本


有时,字体并不能在全部设备上都达到最佳的显示,因此可让设备浏览器来帮助你:

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

注:请负责任地使用optimizeLegibility。此外IE/Edge不支持text-rendering

使用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 */
}

继承box-sizing


box-sizing继承自html

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

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

设置表格相同宽度


.calendar {
  table-layout: fixed;
}

使用Flexbox来避免Margin Hacks


在作多列布局的时候,能够经过Flexboxspace-between属性来避免nth-first-last-child等hacks:

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

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

对空连接使用属性选择器


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

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

文本溢出省略的处理方法

单行文本溢出

.inline{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

多行文本溢出

.foo{
    display: -webkit-box!important;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    -webkit-box-orient: vertical;/*方向*/
    -webkit-line-clamp:4;/*显示多少行文本*/
}
相关文章
相关标签/搜索