# 20 个 CSS 快速提升技巧
# 使用 flexbox 布局来避免 margin 的问题
# 使用:not() 解决 lists 边框的问题
在 web 设计中,我们通常使用:last-child nth-child 选择器来覆盖原先声明应在父选择器上的样式。
比如说一个导航菜单,通过使用 borders 来给每个链接 Link 创建分割符,然后再在加上一条规则 解除最后一个 link 的 border
.nav li {
border-right: 1px solid #666;
}
.nav li:last-child {
border-right: none;
}
1
2
3
4
5
6
2
3
4
5
6
.nav li:not(:last-child) {
border-right: 1px solid #666;
}
1
2
3
2
3
# body 上加入 line-height 样式
# 垂直居中任何元素 (vertical-center anything)
html,
body {
height: 100%;
margin: 0;
}
body {
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-flex;
display: flex;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 使用 SVG icons
.logo {
background: url("logo.svg");
}
1
2
3
2
3
温馨提示
如果将 SVG 用在可交互的元素上比如说 button,SVG 会产生无法加载的问题。可以通过下面这个规则来确保 SVG 可以访问到(确保在 HTML 中已设置适当的 aria 属性)
.no-svg .icon-only:after {
content: attr(aria-label);
}
1
2
3
2
3
# 使用 “OWL 选择器”
使用通用选择器(universal selector)* 和相邻的兄弟选择器(adjacent sibling selector)+ 可以提供一个强大的的 CSS 功能,给紧跟其他元素中的文档流中的所有元素设置统一的规则
* + * {
margin-top: 1.5rem;
}
1
2
3
2
3
在上面的列子中,跟在其他元素后面的元素,比如说 H3 后面的 H4,或者一个段落之后的一个段落,他们之间至少 1.5rems 的间距(大约为 30px)
# 一致的垂直结构(Consistent Vertical Rhythm)
# 对更漂亮的换行文本使用 box-decoration-break
假设您希望对换行到多行的长文本行应用统一的间距、边距、突出显示或背景色,但不希望整个段落或标题看起来像一个大块。Box Decoration Break 属性允许您仅对文本应用样式,同时保持填充和页边距的完整性。
如果要在悬停时应用突出显示,或在滑块中设置子文本样式以具有突出显示的外观,则此功能尤其有用:
.p {
display: inline-block;
box-decoration-break: clone;
-o-box-decoration-break: clone;
-webkit-box-decoration-break: clone;
}
1
2
3
4
5
6
2
3
4
5
6
内联块声明允许将颜色、背景、页边距和填充应用于每行文本,而不是整个元素,克隆声明确保将这些样式均匀地应用于每行。
# 等宽表格单元格
.calendar {
table-layout: fixed;
}
1
2
3
2
3
# 强制使用属性选择器显示空链接
这对于通过 CMS 插入的链接特别有用
a[href^="http"]:empty::before {
content: attr(href);
}
1
2
3
2
3
# 样式“默认”链接
a[href]:not([class]) {
color: #999;
text-decoration: none;
transition: all ease-in-out 0.3s;
}
1
2
3
4
5
2
3
4
5
# 风格破碎的图像
img {
display: block;
font-family: Helvetica, Arial, sans-serif;
font-weight: 300;
height: auto;
line-height: 2;
position: relative;
text-align: center;
width: 100%;
}
img:before {
content: "We're sorry, the image below is missing :(";
display: block;
margin-bottom: 10px;
}
img:after {
content: "(url: " attr(src) ")";
display: block;
font-size: 12px;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 使用 rem 进行全局大小调整;使用 em 进行局部大小调整
# 隐藏未静音的自动播放视频
video[autoplay]:not([muted]) {
display: none;
}
1
2
3
2
3
# 灵活运用 root 类型
:root {
font-size: calc(1vw + 1vh + 0.5vmin);
}
1
2
3
2
3
# 在表单元素上设置字体大小,以获得更好的移动体验
input[type="text"],
input[type="number"],
select,
textarea {
font-size: 16px;
}
1
2
3
4
5
6
2
3
4
5
6