####使用CSS复位
css复位可以在不同的浏览器上保持一致的样式风格,可以使用css reset库的Normalize等,也可使用更简化的复位方法:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
现在元素margin和padding为0,box-sizing可以设置css盒模型布局。
####继承box-sizing
从html元素继承box-sizing:
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
####使用:not()选择器来决定表单是否显示边框
先为元素添加边框:
/* 添加边框 */
.nav li {
border-right: 1px solid #666;
}
为最后一个元素去除边框:
/* 去掉边框 */
.nav li:last-child {
border-right: none;
}
另一种方法,使用:not()伪类来达到同样的效果:
.nav li:not(:last-child) {
border-right: 1px solid #666;
}
####垂直居中任何元素
html, body {
height: 100%;
margin: 0;
}
body {
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-flex;
display: flex;
}
####逗号分隔列表
使列表的每项都由逗号分隔:
ul > li:not(:last-child)::after {
content: ",";
}
####用负的 nth-child 来选择元素
用负的 nth-child 可以选择 1 至 n 个元素。
li {
display: none;
}
/* 选择第 1 至第 3 个元素并显示出来 */
li:nth-child(-n+3) {
display: block;
}
####使用SVG图标
.logo {
background: url("logo.svg");
}
svg在所有分辨率下都可以良好缩放。
####用max-height来建立纯css的滑块
max-height和overflow hidden来建立纯css的滑块:
.slider {
max-height: 200px;
overflow-y: hidden;
300px;
}
.slider:hover {
max-height: 600px;
overflow-y: scroll;
}
鼠标移入滑块元素时增大它的 max-height 值,便可以显示溢出部分。
####创造格子等宽的表格
table-layout: fixed 可以让每个格子保持等宽:
.calendar {
table-layout: fixed;
}
####用flexbox去除多余的外边距
与其使用 nth-, first-, 和 last-child 去除列之间多余的间隙,不如使用 flexbox 的 space-between 属性:
.list {
display: flex;
justify-content: space-between;
}
.list .person {
flex-basis: 23%;
}
列之间的间隙总是均匀相等。
####利用属性选择器来选择空链接
当 元素没有文本内容,但有 href 属性的时候,显示它的 href 属性:
a[href^="http"]:empty::before {
content: attr(href);
}
####给“默认”链接定义样式
a[href]:not([class]) {
color: #008000;
text-decoration: underline;
}
####一致垂直节奏
通用选择器 (*) 跟元素一起使用,可以保持一致的垂直节奏:
.intro > * {
margin-bottom: 1.25rem;
}
####固定比例盒子
要创建具有固定比例的一个盒子,所有你需要做的就是给 div 设置一个 padding:
.container {
height: 0;
padding-bottom: 20%;
position: relative;
}
.container div {
border: 2px dashed #ddd;
height: 100%;
left: 0;
position: absolute;
top: 0;
100%;
}
使用20%的padding-bottom使得框等于其宽度的20%的高度。与视口宽度无关,子元素的div将保持其宽高比(100%/ 20%= 5:1)。
####用rem来调整全局大小;用em来调整局部大小
在根元素设置基本字体大小后 (html { font-size: 100%; }), 使用 em 设置文本元素的字体大小:
h2 {
font-size: 2em;
}
p {
font-size: 1em;
}
然后设置模块的字体大小为 rem:
article {
font-size: 1.25rem;
}
aside .module {
font-size: .9rem;
}
####隐藏没有静音、自动播放的影片
video[autoplay]:not([muted]) {
display: none;
}
####使用选择器:root来控制字体弹性
在响应式布局中,字体大小应需要根据不同的视口进行调整。你可以计算字体大小根据视口高度的字体大小和宽度,这时需要用到:root:
:root {
font-size: calc(1vw + 1vh + .5vmin);
}
现在,可以使用root em:
body {
font: 1rem/1.6 sans-serif;
}
####为更好的移动体验,为表单元素设置字体大小
当触发的下拉列表时,为了避免表单元素在移动浏览器(ios Safari 等等)上的缩放,加上font-size:
input[type="text"],
input[type="number"],
select,
textarea {
font-size: 16px;
}
原文地址: